java – SPRING:向spring security用户添加自定义用户详细信息

前端之家收集整理的这篇文章主要介绍了java – SPRING:向spring security用户添加自定义用户详细信息前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我目前正在开发一个 Spring MVC应用程序,我需要在登录时向我的Spring Security登录用户添加一个自定义字段(我插入用户名,密码,自定义值).
用户登录时(例如,通过pricipal.getValue),该值必须在任何地方都可用.

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

任何帮助都会很棒!

解决方法

就像Avinash所说,你可以让你的User类实现UserDetails,你也可以实现UserDetailsS​​ervice并覆盖相应的方法来返回自定义的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<GrantedAuthority> 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<GrantedAuthority> authorities) {
        return new User(user.getUsername(),user.getPassword(),user.isEnabled(),true,authorities);
    }

    private List<GrantedAuthority> buildUserAuthority(Set<UserRole> userRoles) {

        Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();

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

        List<GrantedAuthority> Result = new ArrayList<GrantedAuthority>(setAuths);

        return Result;
    }

}

您只需使用自定义UserdetailsS​​ervice配置WebConfigurerAdapter:

@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实现的示例:
custom UserDetails

原文链接:https://www.f2er.com/java/128006.html

猜你在找的Java相关文章