Spring Security – How to get the roles assigned to user

Tags: , , ,



I am implementing JWT Role Based Authorization. I am testing my apis through postman.

The users first makes a POST request and registers itself where we pass in the firstname, empid and password. The user on successfull registarion returns a response including a column roles which is null in the starting. Then I manually assign the user role. I have two roles in myROLE table i.e ADMIN or USER which I assign them manually.

After this, the user needs to authenticate or sign in in order for the token to be gnenrated.

Upto this point everything is correct. The token is being generated but it returns me the roles values null even though I have assigned the user ADMIN role manually. How do I get the roles assigned to user? please help. I am pasting some code below:

Below is my api for user authentication : AuthenticationController

    final Authentication authentication = authenticationManager.authenticate(
            new UsernamePasswordAuthenticationToken(
                authenticationRequest.getEmpID(),
                authenticationRequest.getPswd()
            )
    );
    SecurityContextHolder.getContext().setAuthentication(authentication);
    
    final String token = jwtTokenUtil.generateToken(userDetails 
      ,authentication);


    List<String> roles = authentication.getAuthorities().stream()
    .map(item -> item.getAuthority())
    .collect(Collectors.toList()); 

      

As you can see here I have roles defined. How do I get the roles when authenticating the user?

I added this as mentioned above:

 List<String> roles = authentication.getAuthorities().stream()
    .map(item -> item.getAuthority())
    .collect(Collectors.toList()); 

It does not seem to do anything. What else I am missing?

Users.java:

public class Users {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "USER_ID")
private Long id;

//other columns

@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "CONFIG_USERROLE", joinColumns = @JoinColumn(name = 
"USER_ID"), inverseJoinColumns = @JoinColumn(name = "ROLE_ID"))
private Set<Role> roles; 

public Users(){

}

Role.java:

 public class Role {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ROLE_ID")
private Long id;

@Column(name = "ROLE")
private String role;

Answer

You need to set the roles in your UserDetailsWithToken to get them on the response object. They are only set on the JWT object.

Just add the following line to your AuthenticationController, after obtaining the roles list

UserDetailsWithToken.setRoles(roles);


Source: stackoverflow