MDP
MDP

Reputation: 4267

How to know all roles a user has in Spring security

I use Spring security so log in on the site I'm building to study Spring. I used Hibernate to map User object to other objects that allow user to see or not pages, according to its role. It works.

I was asking if I can know by using authorities-by-username-query, all the role a single user has, instead of checking my User object. This is my query:

        authorities-by-username-query="select u1.utente, 
        u1.email, u2.descrizione, u3.id_autorizzazioni,
        u3.autorizzazione from autenticazione u1,
        autorizzazione u2, autorizzazioni
        u3 where u1.utente = u3.utente and 
        u2.id_autorizzazione = u3.autorizzazione and u1.email =?"

If I write that query on mysql console I get 3 records, so the query it's right.

This is my database

enter image description here

I used Collection<SimpleGrantedAuthority> authorities = (Collection<SimpleGrantedAuthority>) SecurityContextHolder.getContext().getAuthentication().getAuthorities(); but I always get a collection that have size 1 instead of 3 (I have 3 roles in the db for the user, as you can see in the pic). I don't understand if it depends on my db or my authorities-by-username-query. Probably one of the two things is wrong

Upvotes: 0

Views: 6921

Answers (2)

Ralph
Ralph

Reputation: 120861

You can use two different approaches:

  • query for the user roles (of any user) in the database
  • "look" in the Session to get the roles of the current user

For the first approach it is possible to invoke the UserDetailsService.loadUserByUsername(String username) method.

For the second approach: SecurityContextHolder.getContext().getAuthentication().getAuthorities();

Upvotes: 0

Ankur Singhal
Ankur Singhal

Reputation: 26077

You can use SecurityContextHolder.getContext().getAuthentication().getAuthorities() to obtain a collection of the currently logged in user's roles.

Collection<SimpleGrantedAuthority> authorities = (Collection<SimpleGrantedAuthority>)    SecurityContextHolder.getContext().getAuthentication().getAuthorities();

You have the collection of roles in the authorities variable.

Little bit more excercise

private boolean hasRole(String role) {
  Collection<GrantedAuthority> authorities = (Collection<GrantedAuthority>)
  SecurityContextHolder.getContext().getAuthentication().getAuthorities();
  boolean hasRole = false;
  for (GrantedAuthority authority : authorities) {
     hasRole = authority.getAuthority().equals(role);
     if (hasRole) {
      break;
     }
  }
  return hasRole;
}

Upvotes: 2

Related Questions