Tutorial

Spring Security Role Based Access Authorization Example

Published on August 3, 2022
author

Rambabu Posa

Spring Security Role Based Access Authorization Example

Today we will look into spring security role based access and authorization example. However before reading this post, please go through my previous post about “Spring 4 Security MVC Login Logout Example” to get some basic knowledge about Spring 4 Security.

Spring Security Role

In this post, we will discuss how to define, use and manage spring security roles like “USER”, “ADMIN” in Spring Web Application. Like my previous post, this post example is also using Spring 4 MVC Security with In-Memory Store and Spring Java Configuration Feature to develop the application. That means we are not going to use web.xml file and also not writing even single line of Spring XML Configuration. We will use “In-Memory Store” option to store and manage User Credentials. We are going to use Spring 4.0.2.RELEASE, Spring STS 3.7 Suite IDE, Spring TC Server 3.1 with Java 1.8 and Maven build tool to develop this example.

Spring Security Role Based Access Authorization Example

  1. Create a “Simple Spring Web Maven” Project in Spring STS Suite with the following details. Project Name : SpringMVCSecruityMavenRolesApp2. Use same pom.xml file from my previous post with the following changes
<artifactId>SpringMVCSecruityMavenRolesApp</artifactId>

<build>
  <finalName>SpringMVCSecruityMavenRolesApp</finalName>
</build>
</project>
  1. Use all Java and JSP files from my previous post. We will discuss only updated or newly added content here.
  2. Update LoginSecurityConfig.java file to configure User roles like “USER” and “ADMIN”. LoginSecurityConfig.java
package com.journaldev.spring.secuity.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class LoginSecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder authenticationMgr) throws Exception {
		authenticationMgr.inMemoryAuthentication()
			.withUser("jduser").password("jdu@123").authorities("ROLE_USER")
			.and()
			.withUser("jdadmin").password("jda@123").authorities("ROLE_USER","ROLE_ADMIN");
	}
	
	@Override
	protected void configure(HttpSecurity http) throws Exception {

		
		http.authorizeRequests()
			.antMatchers("/homePage").access("hasRole('ROLE_USER') or hasRole('ROLE_ADMIN')")
			.antMatchers("/userPage").access("hasRole('ROLE_USER')")
			.antMatchers("/adminPage").access("hasRole('ROLE_ADMIN')")
			.and()
				.formLogin().loginPage("/loginPage")
				.defaultSuccessUrl("/homePage")
				.failureUrl("/loginPage?error")
				.usernameParameter("username").passwordParameter("password")				
			.and()
				.logout().logoutSuccessUrl("/loginPage?logout"); 
		
	}
}

Code Explanation

  1. In configureGlobal() method, we have added two users: One user with “ROLE_USER” role and another user with both “ROLE_USER” and “ROLE_ADMIN” roles. That means this second user will act as a Admin User. Like this we can configure any number of users and roles.
  2. We can use either authorities(ROLE) or roles(ROLE) methods to configure Roles in our application.
  3. Difference between authorities() and roles() methods:
  • authorities() needs complete role name like “ROLE_USER”
  • roles() needs role name like “USER”. It will automatically adds “ROLE_” value to this “USER” role name.
  1. In configure() method, we have defined different URLs with required Access Roles.
antMatchers("/homePage")
   .access("hasRole('ROLE_USER') or hasRole('ROLE_ADMIN')")

This code snippet configures that “/homePage” is available for both USER and ADMIN Roles.

 .antMatchers("/userPage").access("hasRole('ROLE_USER')")
 .antMatchers("/adminPage").access("hasRole('ROLE_ADMIN')")

This code snippet configures that “/userPage” is accessible by “USER” role only and .“/adminPage” is accessible by “ADMIN” role only. If other roles access these pages, we will get access “403 Access is Denied” Error message.

  1. Update LoginController.java Controller file to define new URL access paths as shown below. LoginController.java
package com.journaldev.spring.web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class LoginController {

	@RequestMapping(value = { "/"}, method = RequestMethod.GET)
	public ModelAndView welcomePage() {
		ModelAndView model = new ModelAndView();
		model.setViewName("welcomePage");
		return model;
	}

	@RequestMapping(value = { "/homePage"}, method = RequestMethod.GET)
	public ModelAndView homePage() {
		ModelAndView model = new ModelAndView();
		model.setViewName("homePage");
		return model;
	}
	
	@RequestMapping(value = {"/userPage"}, method = RequestMethod.GET)
	public ModelAndView userPage() {
		ModelAndView model = new ModelAndView();
		model.setViewName("userPage");
		return model;
	}
	
	@RequestMapping(value = {"/adminPage"}, method = RequestMethod.GET)
	public ModelAndView adminPage() {
		ModelAndView model = new ModelAndView();
		model.setViewName("adminPage");
		return model;
	}
	
	@RequestMapping(value = "/loginPage", method = RequestMethod.GET)
	public ModelAndView loginPage(@RequestParam(value = "error",required = false) String error,
	@RequestParam(value = "logout",	required = false) String logout) {
		
		ModelAndView model = new ModelAndView();
		if (error != null) {
			model.addObject("error", "Invalid Credentials provided.");
		}

		if (logout != null) {
			model.addObject("message", "Logged out from JournalDEV successfully.");
		}

		model.setViewName("loginPage");
		return model;
	}

}

Code Explanation In addition to the previous post Example, here we have added two more new URLs.

  1. “/userPage” is used by USER Role to access and perform Normal user activities.

  2. “/adminPage” is used by ADMIN Role to access and perform Admin user activities. ADMIN role can access “/userPage” URL too.

  3. Updated homePage.jsp file to provide User and Admin Roles specific activities. homePage.jsp

<%@taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core"%>
<a href="${pageContext.request.contextPath}/userPage">JD User</a> | <a href="${pageContext.request.contextPath}/adminPage">JD Admin</a> | <a href="javascript:document.getElementById('logout').submit()">Logout</a>

<h3>Welcome to JournalDEV Tutorials</h3>
<ul>
   <li>Java 8 tutorial</li>
   <li>Spring tutorial</li>
   <li>Gradle tutorial</li>
   <li>BigData tutorial</li>
</ul>

<c:url value="/logout" var="logoutUrl" />
<form id="logout" action="${logoutUrl}" method="post" >
  <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
</form>

Here we have add three Menu like options at top frame. “Logout” is already discussed in my previous post. New two links are:

  1. JD User: Accessible by both “USER” and “ADMIN” Roles
  2. JD Admin: Accessible only by both “ADMIN” Roles

NOTE:- In Real-time applications, we will show only “JD User” link to “USER” Role and hide “JD Admin” link. To test whether it is accessible by “USER” Role or not and also to see the exact error message, we have not hidden this link.20. Add new adminPage.jsp file to act as a Homepage for “ADMIN” role. adminPage.jsp

<%@taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core"%>
<h3>Welcome to JournalDEV Tutorials</h3>
<h3>Admin Page</h3>

<c:url value="/logout" var="logoutUrl" />
<form id="logout" action="${logoutUrl}" method="post" >
  <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
</form>
<c:if test="${pageContext.request.userPrincipal.name != null}">
	<a href="javascript:document.getElementById('logout').submit()">Logout</a>
</c:if>
  1. Add new userPage.jsp file to act as a Homepage for “USER” role. userPage.jsp
<%@taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core"%>
<h3>Welcome to JournalDEV Tutorials</h3>
<h3>User Page</h3>

<c:url value="/logout" var="logoutUrl" />
<form id="logout" action="${logoutUrl}" method="post" >
  <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
</form>
<c:if test="${pageContext.request.userPrincipal.name != null}">
	<a href="javascript:document.getElementById('logout').submit()">Logout</a>
</c:if>

We have completed our application development now. It’s time to see our project final structure and test the application.26. Final Project Structure looks like this: spring security roles example

Spring Security Roles Example Application Test

  1. Right Click on Project in Spring STS IDE and select “Run AS >> Run on Server” option. It will access default Application welcome page as shown below: security security  role login inmemory example3. Click on “Login to JournalDEV” link.Now you are at Login Page. Spring Security Role Based Access Authorization Example5. First login with “USER” Role Credentials: Username: jduser Password: jdu@123 Spring Security Role Now we will see Application HomePage with 3 Menu Options: “JD User”, “JD Admin” and “Logout”. Click on “JD User” link. As we have logged into application using “USER” Role Credentials, We can access this link as shown below. Spring Security Role Based Access Just use backword arrow in Spring STS IDE and this time click on “JD Admin” Link. Spring Security Roles As we have logged in with “USER” Role Credentials, We cannot access this link. That’s why we saw this error message: “403 Access is denied”.9. Now Logged and again login with ADMIN Role Credentials Username: jdadmin Password: jda@123 This time we can access “JD Admin” Link successfully as shown below. Spring Security Roles Example Test “Logout” link to Logged out of the Application.

That’s all about Spring security roles example to provide authorised access to web application pages.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Rambabu Posa

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
August 25, 2015

Nice work, it is a good starter for Spring-Security module. I wanted to try it myself so I prepared my own project on github (https://github.com/arnosthavelka/security-poc/tree/spring-boot-%26-in-memory-security). I made several improvements & changes: * @Import is not necessary * Controller is reduced just for /login (the rest is moved to MVC config since it is just mapping) * optimized security settings * internationalization * changed to Spring Boot (the worst problem :-)) My project is heavily based on your sources, but it is available complete.

- Arny

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    July 5, 2016

    It would be nice if you would use real code instead of the " everwhere.

    - me

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      August 6, 2016

      hi how to allow role_user to some get url… and some all (get, post, put, delete) to admin role

      - marc

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        November 3, 2016

        Hi, Thanks for this tutorial. Good explanation. If possible, can you please develop and deliver a Spring Security + LDAP + SSO + Tomcat 8 example at the earliest.

        - Bhanu Dhulipudi

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          January 6, 2017

          Hi, what i am doing is i have a user who has many roles some of which are ROLE_ADMIN and ROLE_DBA. in spring-security xml i have configured intercept url like when I log in i can access url /admin/** but I cant access url /dba/** even i have ROLE_DBA in list of GrantedAuthoriy while creating UserDetail object in UserDetailService. Thank you

          - Rohit

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            August 30, 2017

            Hi, Great airticle.

            - sdfs

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              December 2, 2017

              Hi! Suppose the link that the admin can access needs to display all the users with USER role, how would you get the list of user from in memory authentication? I’m trying to achieve this in my app. Any help will be much appreciated

              - Kunal

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                December 22, 2017

                Can we have a session management according to the user roles

                - Krish

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  October 10, 2018

                  name=“${_csrf.parameterName}” value="${_csrf.token} is not necessary if you are using Spring tag libs. Specifically spring tag lib for form Then the tag changes to

                  - rajeev

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    October 25, 2018

                    where is source code sir

                    - Naguru

                      Try DigitalOcean for free

                      Click below to sign up and get $200 of credit to try our products over 60 days!

                      Sign up

                      Join the Tech Talk
                      Success! Thank you! Please check your email for further details.

                      Please complete your information!

                      Become a contributor for community

                      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                      DigitalOcean Documentation

                      Full documentation for every DigitalOcean product.

                      Resources for startups and SMBs

                      The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                      Get our newsletter

                      Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                      New accounts only. By submitting your email you agree to our Privacy Policy

                      The developer cloud

                      Scale up as you grow — whether you're running one virtual machine or ten thousand.

                      Get started for free

                      Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                      *This promotional offer applies to new accounts only.