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

我目前正在使用Spring MVC应用程序,我需要在登录时向我的Spring

Security登录用户权限添加自定义字段(我输入用户名,密码,自定义值)。用户登录时,该值必须在任何地方都可用(例如,通过pricipal.getValue)。

我阅读了很多有关自定义用户类和自定义服务的信息,但实际上找不到适合我的问题的有效解决方案…

任何帮助将是巨大的!

回答:

就像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<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;

}

}

您只需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 ...//

}

}

以上是 SPRING:向Spring Security用户添加自定义用户详细信息 的全部内容, 来源链接: utcz.com/qa/426211.html

回到顶部