@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;
}
}
5条答案
按热度按时间bq3bfh9z1#
就像Avinash说的,你可以让你的
User
类实现UserDetails
,你也可以实现UserDetailsService
并重写相应的方法来返回自定义的User
对象:字符串
您只需使用自定义
UserdetailsService
配置WebConfigurerAdapter
:型
下面是一个定制
UserDetails
实现的示例:custom UserDetails8ulbf1ek2#
创建实现
UserDetails
接口的类。字符串
然后,一旦经过身份验证,您就可以像这样在项目中的任何位置访问此对象。
型
8xiog9wr3#
我是这样做的。
AccountDetailsService.java
字符串
CustomUserDetails.java
型
brgchamk4#
如果你想把角色写为
ADMIN/USER
,不要直接写userRole.getRole()
,而是写为"ROLE_" + userRole.getRole()
,这样你的代码就可以无错误地运行。示例:
字符串
icomxhvb5#
它没有实现接口
UserDetails
,而是通过扩展类org.springframework.security.core.userdetails.User
更干净和简单。字符串
然后,一旦经过身份验证,您就可以像这样在项目中的任何位置访问此对象。
型