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

2022-09-02 11:49:27

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

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

任何帮助都会很棒!


答案 1

就像Avinash说的,你可以让你的类实现,你也可以实现和重写相应的方法来返回自定义对象:UserUserDetailsUserDetailsServiceUser

@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, true, 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;
    }

}

您只需使用自定义配置:WebConfigurerAdapterUserdetailsService

@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


答案 2

创建类实现接口。UserDetails

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

然后,一旦经过身份验证,您就可以像这样访问项目中的任意位置的此对象。

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

推荐