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?
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.
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.
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"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With