How to Access Roles and User Details Using Spring Security

By Arvind Rai, November 27, 2019
In Spring Security, it may require to show some zones on the basis of access roles. We need role details and user details to decide which zone should be shown. In JSP and Spring controller, at both place we may require roles and user details. So on this page we will learn in details how to access roles and user details in JSP and Spring controller. Find the configured users and roles.
  <http auto-config="true">
	<intercept-url pattern="/login" access="ROLE_USER,ROLE_SUPERVISOR" />
	<logout logout-success-url="/login" />
  <password-encoder hash="sha"/>
	<user name="ram" password="0733824cc1549ce36139e8c790a9344d1e385cd2" authorities="ROLE_USER" />
	<user name="shyam" password="0733824cc1549ce36139e8c790a9344d1e385cd2" authorities="ROLE_SUPERVISOR" />
 <beans:bean id="webSecurityExpressionHandler" class="" />   
Two user ram and shyam has been configured with password con1234 . Ram has ROLE_USER and shyam has ROLE_SUPERVISOR.

How to Access Role in JSP Using Spring Security

To access roles in JSP we need to configure the security tag library. The required jar dependency must be there in you lib directory.
So start configuring tag library in jsp as below and use it.
<%@ taglib uri="" prefix="security" %>
 <security:authorize access="hasRole('ROLE_SUPERVISOR')">
This zone will be visible to Supervisor only.<br/>
You have Supervisor role.<br/>
 <a href="j_spring_security_logout">logout </a>
You need to configure a bean as below
 <beans:bean id="webSecurityExpressionHandler" class="" />  
If you will not configure it then you will get the below error. No visible WebSecurityExpressionHandler instance could be found in the application context.

When we access the URL
and login with shyam/con1234 user, we will see the below UI.

How to Access Roles and User Details Using Spring Security

SecurityContextHolder in Spring Security

Spring security SecurityContextHolder will help to access roles and user details in Spring controller. SecurityContextHolder provides the context of Spring controller and that provides authentication and authorization details. Now we will see a method implementation to access roles and user details.

How to Access Role in Controller Using Spring Security

Find the method that will check if provided role has access or not.
private boolean hasRole(String role) {
  Collection<GrantedAuthority> authorities = (Collection<GrantedAuthority>)
  boolean hasRole = false;
  for (GrantedAuthority authority : authorities) {
     hasRole = authority.getAuthority().equals(role);
     if (hasRole) {
  return hasRole;

How To Get User Details using Spring Security

Find the method that will provide the user details.
private void getUserDetails() {
   UserDetails userDetails = (UserDetails)SecurityContextHolder.getContext().

Download Source Code


©2023 | Privacy Policy | Contact Us