当前位置:  开发笔记 > 编程语言 > 正文

SPRING:向Spring安全用户添加自定义用户详细信息

如何解决《SPRING:向Spring安全用户添加自定义用户详细信息》经验,为你挑选了2个好方法。

我目前正在开发一个Spring MVC应用程序,我需要在登录时向我的Spring Security登录用户添加一个自定义字段(我插入用户名,密码,自定义值).当用户登录时(例如,通过pricipal.getValue),该值必须在任何地方都可用.

我阅读了很多关于自定义用户类和自定义服务的内容,但无法真正找到解决问题的解决方案......

任何帮助都会很棒!



1> 小智..:

就像Avinash所说,你可以创建User类实现UserDetails,你也可以实现UserDetailsService和覆盖相应的方法来返回自定义User对象:

@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {

    //get user from the database, via Hibernate
    @Autowired
    private UserDao userDao;

    @Transactional(readOnly=true)
    @Override
    public UserDetails loadUserByUsername(final String username)
        throws UsernameNotFoundException {
//CUSTOM USER HERE vvv
        User user = userDao.findByUserName(username);
        List authorities =
                                      buildUserAuthority(user.getUserRole());
//if you're implementing UserDetails you wouldn't need to call this method and instead return the User as it is
        //return buildUserForAuthentication(user, authorities);
return user;

    }

    // Converts user to spring.springframework.security.core.userdetails.User
    private User buildUserForAuthentication(user,
        List authorities) {
        return new User(user.getUsername(), user.getPassword(),
            user.isEnabled(), true, true, true, authorities);
    }

    private List buildUserAuthority(Set userRoles) {

        Set setAuths = new HashSet();

        // add user's authorities
        for (UserRole userRole : userRoles) {
            setAuths.add(new SimpleGrantedAuthority(userRole.getRole()));
        }

        List Result = new ArrayList(setAuths);

        return Result;
    }

}

您只需WebConfigurerAdapter使用自定义配置您UserdetailsService:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
@Qualifier("userDetailsService")
UserDetailsService userDetailsService;

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}

@Override
protected void configure(HttpSecurity http) throws Exception {

    //authorization logic here ...
}

    @Bean
    public PasswordEncoder passwordEncoder(){
        // return preferred PasswordEncoder ...//
    }


}

这是自定义UserDetails实现的示例: 自定义UserDetails



2> Avinash..:

创建类实现UserDetails接口.

public class User implements UserDetails {
    // Your user properties
    // implement methods
}

然后,一旦通过身份验证,您就可以像这样访问项目中的任何位置.

User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

推荐阅读
yzh148448
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有