获取userdetails权限

cvxl0en2  于 2021-07-14  发布在  Java
关注(0)|答案(3)|浏览(378)

我创造了一个 @ManyToMany table。一个表中的用户和另一个表中的角色。也就是说,一个用户可以有多个角色,而一个角色可以有多个用户。我认为没有什么不寻常或错误。
我就是这样得到的 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);

        }

    }
ubbxdtey

ubbxdtey1#

你需要修改你的密码 getAuthoritiesEntities ```
private List getAuthoritiesEntities(Set userRoles) {
Set 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);
ruoxqz4g

ruoxqz4g2#

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;
        }
2jcobegt

2jcobegt3#

你可以打电话 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());
    }

相关问题