javaspringspring-mvcspring-securityuserdetailsservice

GET UserDetails Authorities


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("va@va.va", "1111",
                    true, true, true, true, roleList);

        }


    }

Solution

  • 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);