Open In App

Example of RBAC in Spring Security

Last Updated : 20 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Role-based role control (RBAC) is a widely used method for managing resource availability in a system. When we use RBAC in Spring Security, we focus on defining roles and it can assign permissions to those roles and then associate users with specific roles.

Key Terminologies

  • Granted Authority: Permission is often represented as an approved authority. These are specific permissions associated with the user, describing the actions that can be performed.
  • Authentication: Authentication is the process of verifying the identity of the user. Once authenticated, the system assigns the appropriate roles and permissions to the user based on their credentials.
  • Access Control List (ACL): An ACL is a list of permissions attached to an object, specifying which users or system roles are allowed access to the object and what operations are allowed on it This helps to control access to resources of an application.

Implementation Steps:

In Spring Security, RBAC (Role-Based Access Control) is set up using configuration classes and annotations to manage security rules and access control logic.

  • Defining Roles and Permissions: Identify the various roles and permissions required in the system, either through code or configuration.
  • Configuring Security Rules: Establish security rules within Spring Security to regulate access based on roles and permissions. This involves specifying URL patterns and determining which roles are needed to access them.
  • Mapping Users to Roles: Connect users with specific roles based on their responsibilities or access needs. This linkage can be static, defined in configuration, or dynamic, fetched from databases.
  • Implementing Authorization Logic: Create logic in the application to verify if users have the necessary roles and permissions for specific actions or resource access. This ensures proper access control based on user roles and permissions.

Implementation of the RBAC in Spring Security

Below are the steps to implement RBAC (Role-Based Access Control) in Spring Security

Step 1: Create a new Spring Boot project using the Spring Initializr and include the specified dependencies, follow these steps:

Dependencies

  • Spring Web
  • Spring Security
  • Lombok

Once the project is created, the file structure will resemble the image below.Folder Structure

Step 2: Open the application.properties file and add the server port connection properties to the project.

spring.application.name=spring-security-RBAC-demo
server.port=8080

Step 3: Create the Security Configuration

We'll create a configuration class to configure Spring Security for the Spring application.

Go to src > org.example.springsecurityrbacdemo > config > SecurityConfig and put the below code.

Java
package org.example.springsecurityrbacdemo.config;


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.web.SecurityFilterChain;
import org.springframework.stereotype.Component;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .requestMatchers("/admin/**").hasRole("ADMIN")
                .requestMatchers("/user/**").hasRole( "USER")
                .anyRequest().authenticated()
                .and()
                .formLogin()
               // Specify the URL for the registration page

                .and()
                .logout().logoutSuccessUrl("/").permitAll();

        return http.build();
    }
    
}

Step 3: Create the User Details Configuration

We'll create a configuration class to configure the credentials for Spring Security in the Spring application.

Go to src > org.example.springsecurityrbacdemo > config > UserDetailsCofig and put the below code.

Java
package org.example.springsecurityrbacdemo.config;

import org.springframework.beans.factory.annotation.Autowired;
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.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.provisioning.UserDetailsManager;

@Configuration
public class UserDetailsConfig {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public UserDetailsManager userDetailsManager() {
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        manager.createUser(
                User.withUsername("admin")
                        .password(passwordEncoder().encode("admin"))
                        .roles("ADMIN")
                        .build()
        );
        manager.createUser(
                User.withUsername("user")
                        .password(passwordEncoder().encode("user"))
                        .roles("USER")
                        .build()
        );
        return manager;
    }
}

Step 4: Create the Admin Controller class

Go to src > org.example.springsecurityrbacdemo > controller > AdminController and put the below code.

Java
package org.example.springsecurityrbacdemo.controller;

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

@RestController
@RequestMapping("/admin")
public class AdminController {
    @GetMapping("/dashboard")
    public String admin() {
        return "Welcome Admin!";
    }

}

Step 5: Create the User Controller class

Go to src > org.example.springsecurityrbacdemo > controller > UserController and put the below code.

Java
package org.example.springsecurityrbacdemo.controller;

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

@RestController
@RequestMapping("/user")
public class UserController {
    
    @GetMapping("/home")
    public String user() {
        return "Welcome User!";
    }
}

Step 6: Main Class

No need to change the main class of the application.

Java
package org.example.springsecurityrbacdemo;

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

@SpringBootApplication
public class SpringSecurityRbacDemoApplication {

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

}

Step 7: Run the Application

Once we run the application, then the project will run at port 8080.

Application Started

Login into the Admin Credientials

Login Dashboard

  • username: admin
  • password: admin

Access the below url:

http://localhost:8080/admin/dashboard

Output:

Admin Dashboard

http://localhost:8080/user/home

Output:

Error Page


Unauthorized access occurs when attempting to access the user home page, as it is only permitted for the admin, thus preventing access to the URL.

UserLogin Credientials

  • username: user
  • password: user

Access the Admin Dashboard:

http://localhost:8080/admin/dashboard

Accessing Admin Dashboard


Unauthorized request because it only gives permission to access the admin.

http://localhost:8080/user/home

Output:

Output in Browser


The above example demonstrates basic setup for RBAC using Spring Security in a Java web application.


Next Article

Similar Reads