Spring Security role based authorization example

Posted by Fabis94 on Fri, 04 Feb 2022 13:08:43 +0100

This guide shows you how to Spring Security Configure role-based authorization in. To use Spring Security authorization, we must override and authorize each requested method according to the logged in user role. configure(HttpSecurity http)WebSecurityConfigurerAdapter

What will we build

In this example, we will create a Spring Boot application and authorize each request according to the logged in user role. To do this, we need the following:

1. The role assigned to the user who is authorized to access the URL / page:

private static final String ROLE_1 = "ADMIN";
private static final String ROLE_2 = "USER";
copy

2. Users with different roles:

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {		
	auth.inMemoryAuthentication()
			.withUser("admin")
			.password(passwordEncoder().encode("admin@123"))
			.roles(ROLE_1)
			.and()
			.withUser("user")
			.password(passwordEncoder().encode("user@123"))
			.roles(ROLE_2);
}
copy

For demonstration purposes, we used in memory authentication.

3. Authorize each request according to the logged in user role:

@Override
protected void configure(HttpSecurity http) throws Exception {
	http.authorizeRequests()
			.antMatchers("/admin").hasRole(ROLE_1)
			.antMatchers("/user").hasAnyRole(ROLE_2, ROLE_1)
			.antMatchers("/all").permitAll()
			.and().formLogin();	
}
copy

4. And some endpoints accessed by users according to the assigned roles.

Similar posts:

  1. Spring Boot + Spring Security with JPA authentication and MySQL
  2. Spring Security JDBC authentication using Spring Boot

Technology used

Find a list of all technologies used in this application.

  1. Spring tool kit 4
  2. JDK 8
  3. Spring Boot 2.1.7.RELEASE
  4. Spring Security 5.1.6.RELEASE
  5. Maven 3

Required dependencies

To resolve JAR dependencies, add the following code to your POM XML.

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.7.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>
	<groupId>org.websparrow</groupId>
	<artifactId>spring-security-authorization</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>spring-security-authorization</name>
	<description>Demo project for Spring Secuirty Authorization</description>
	<properties>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>
copy

Project structure

The final project structure of our application in STS 4 IDE will be as follows:

Now, let's jump to the actual code section.

1. User endpoint

Create some endpoints / pages for users to access according to the role. In this controller, I created three REST endpoints, namely

  1. /ADMIN → user access role is "ADMIN".
  2. /User → the role accessed by the user is "USER/ADMIN". Of course, ADMIN can access all content.
  3. /All → accessible to all. No login required.
MyController.java
package org.websparrow.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

	@GetMapping("/admin")
	public String admin() {

		return "<h2>Welcome Admin!</h2>";
	}

	@GetMapping("/user")
	public String user() {

		return "<h2>Welcome User!</h2>";
	}

	@GetMapping("/all")
	public String all() {

		return "<h2>Hello Everyone!</h2>";
	}
}
copy

2. Security configuration

In order to restrict users' access, we need to extend the WebSecurityConfigurerAdapter class and override its methods, and authorize each request according to the logged in user role. configure(HttpSecurity http)

1. / ADMIN → user access role is "ADMIN".
2. / user → the user has the role of "USER/ADMIN". Of course, ADMIN can access all content.
3. / all → visited by everyone. No login required.

SecurityConfiguration.java
package org.websparrow.configuration;

import org.springframework.context.annotation.Bean;
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;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
	
	// Roles for users
	private static final String ROLE_1 = "ADMIN";
	private static final String ROLE_2 = "USER";
	
	// In-memory users with roles
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {		
		auth.inMemoryAuthentication()
				.withUser("admin")
				.password(passwordEncoder().encode("admin@123"))
				.roles(ROLE_1)
				.and()
				.withUser("user")
				.password(passwordEncoder().encode("user@123"))
				.roles(ROLE_2);
	}
	
	// Password encoding
	@Bean
	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}

	// Authorized the request based on role
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests()
				.antMatchers("/admin").hasRole(ROLE_1)
				.antMatchers("/user").hasAnyRole(ROLE_2, ROLE_1)
				.antMatchers("/all").permitAll()
				.and().formLogin();
	}
}
copy

Don't forget to add @ Configuration and comments at the class level of the custom security Configuration class@ EnableWebSecurity

3. Run the application

This kind of SecurityApp contains the main methods and is responsible for starting the application.

SecurityApp.java

package org.websparrow;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SecurityApp {

	public static void main(String[] args) {
		SpringApplication.run(SecurityApp.class, args);
	}
}
copy

4. Test application

To test the application, start the Spring Boot application by executing the above class and follow the following steps:

For the / admin page:

  1. Click localhost:8080/admin, which redirects you to Login page.
  2. Log in with a user with the "ADMIN" role. After successful authentication, it will display the management page.
  3. Similarly, if you try to access the management URL with a USER who does not have the "ADMIN" role (the USER has the "USER" role), Spring Security will prevent you from accessing the management page.

For the / user page:

  1. Click localhost:8080/user, which redirects you to Login page.
  2. Log in with a USER with the role "USER". After successful authentication, it will display the USER page.
  3. Users with the administrator role can also access it.

For / all pages:

  1. Spring Security allows everyone to access the localhost:8080/all URL. It does not require authentication.

Download source code: spring-security-role-based-authorization-example.zip

reference resources

  1. Getting started with Spring Security
  2. Spring Security - how to change the default user name and password
  3. Spring Security - authorization request

 

Topics: Java Spring Spring Boot