Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the current user roles from Spring security 3.1

I have loaded the roles from the database for the current user. And I can access the user role with spring security expression in JSP, and can hide the options and URLs which are not authorized with hasRole. Now I wanted to have it in the servlet and display it in the logs (or store in the user object session). How can we achieve it?

like image 686
Bhas Avatar asked Apr 10 '12 16:04

Bhas


People also ask

How do I check my Spring Security role?

The first way to check for user roles in Java is to use the @PreAuthorize annotation provided by Spring Security. This annotation can be applied to a class or method, and it accepts a single string value that represents a SpEL expression.


2 Answers

You can try something like this:

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

You have the collection of roles in the authorities variable.

like image 115
Dani Avatar answered Sep 24 '22 13:09

Dani


If you develop on Java 8, it's getting easier.

To get all user roles:

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();  Set<String> roles = authentication.getAuthorities().stream()      .map(r -> r.getAuthority()).collect(Collectors.toSet()); 

To check if the user has a particular role, for example, ROLE_USER:

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();  boolean hasUserRole = authentication.getAuthorities().stream()           .anyMatch(r -> r.getAuthority().equals("ROLE_USER")); 
like image 21
Bogusz Avatar answered Sep 25 '22 13:09

Bogusz