获取用户详细信息权限



我创建了一个@ManyToMany表。一个表中的用户和另一个表的角色。也就是说,一个用户可以有很多角色,一个角色可以有很多用户。我认为没有什么异常或错误。

这就是我得到roles的方法:

List<AuthoritiesEntity> roleList = userEntity.getAuthoritiesEntities();

我还有UserDetails

因此,我需要以某种方式将这些角色推到UserDetails中,但我做不到。

请告诉我怎么做?

MyUserDetail.java

public class MyUserDetail implements UserDetailsService {

@Autowired
ServiceJpa serviceJpa;

@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {

UserEntity userEntity = serviceJpa.findUserByEmail(email);

List<AuthoritiesEntity> roleList = userEntity.getAuthoritiesEntities();

return new org.springframework.security.core.userdetails.User("va@va.va", "1111",
true, true, true, true, roleList);
}

}

您需要修改getAuthoritiesEntities

private List<GrantedAuthority> getAuthoritiesEntities(Set<Role> userRoles) {
Set<GrantedAuthority> roles = new HashSet<>();
userRoles.forEach((role) -> {
roles.add(new SimpleGrantedAuthority(role.getRole()));
});
List<GrantedAuthority> grantedAuthorities = new ArrayList<>(roles);
return grantedAuthorities;
}

现在get roleList

List<AuthoritiesEntity>roleList=userEntity.getAuthoritiesEntities(userEntity.getRoles());

现在返回身份验证

return new org.springframework.security.core.userdetails.User(userEntity.getUsername(), userEntity.getPassword(), roleList);
private Collection<? extends GrantedAuthority> getAuthorities(Collection<AuthoritiesEntity> roles) {
List<GrantedAuthority> authorities = new ArrayList<>();
for (AuthoritiesEntity authoritiesEntity: roles) {
authorities.add(new SimpleGrantedAuthority(authoritiesEntity.getRoleEnum().toString()));
}
return authorities;
}

您可以调用mapRolesToAuthorites方法,传递roleList并定义这样的函数。

return new org.springframework.security.core.userdetails.User("va@va.va", "1111",
true, true, true, true, mapRolesToAuthorites(roleList));
private Collection<? extends GrantedAuthority> mapRolesToAuthorites(Collection<Role> roles) {
return roles.stream().map(role -> new SimpleGrantedAuthority(role.getName())).collect(Collectors.toList());
}

最新更新