1

我创建了一个@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);

        }


    }
4

3 回答 3

1
    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;
        }
于 2021-04-17T06:30:37.803 回答
1

你需要修改你的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);
于 2021-04-17T06:41:51.300 回答
0

您可以调用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());
    }
于 2021-04-17T05:13:38.130 回答