GET UserDetails Authorities

1.9k Views Asked by At

I created a @ManyToMany table. Users in one table and roles in the other. That is, a user can have many roles, and a role can have many users. I think there is nothing unusual or wrong.

This is how I get roles:

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

I also have UserDetails

And so I need to somehow shove these roles into UserDetails, but I can't.

Please tell me how to do this?

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("[email protected]", "1111",
                    true, true, true, true, roleList);

        }


    }
3

There are 3 best solutions below

1
On BEST ANSWER

You need to modify your 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;
    }

Now get roleList

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

Now return authentication

return new org.springframework.security.core.userdetails.User(userEntity.getUsername(), userEntity.getPassword(), roleList);
0
On
    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;
        }
0
On

You can call mapRolesToAuthorites method and pass your roleList and define a function like this.

return new org.springframework.security.core.userdetails.User("[email protected]", "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());
    }