Comprehensive Guide: Implementing RBAC with Spring Security and JWT

This article walks through the fundamentals of Role‑Based Access Control (RBAC), explains the RBAC0‑RBAC3 model hierarchy, demonstrates how to configure Spring Security for in‑memory and database authentication, integrates JWT for stateless token handling, and shows how to enable JSON‑based login and BCrypt password encryption with concrete code examples.

Architect's Guide
Architect's Guide
Architect's Guide
Comprehensive Guide: Implementing RBAC with Spring Security and JWT

RBAC (Role‑Based Access Control) is introduced as a method of linking users to roles and roles to permissions, allowing indirect assignment of permissions to users. The article first defines RBAC and presents a mind‑map illustration.

RBAC Model Classification

The four RBAC models are described:

RBAC0 : the basic model, supporting both many‑to‑one and many‑to‑many relationships between users and roles. Example: a user "Zhang San" holds both an administrative and a financial role, thus acquiring two separate permission sets.

RBAC1 : adds role hierarchy (sub‑roles) and inheritance.

RBAC2 : extends RBAC0 with constraints such as role mutual exclusion, cardinality limits, prerequisite roles, and runtime separation. Each constraint is illustrated with a concrete scenario (e.g., a user cannot simultaneously hold "accountant" and "auditor" roles).

RBAC3 : combines RBAC1 and RBAC2 into a unified model.

User Group Usage

Grouping users enables batch granting of roles, reducing repetitive work when many users share the same role (e.g., assigning a role to ten thousand employees in a department).

Simple Spring Security Example

Steps to add Spring Security:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-security</artifactId>
  <version>2.3.1.RELEASE</version>
</dependency>

Define a REST controller, then configure in‑memory authentication:

package com.example.demo.web;

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

@RestController
@RequestMapping("/test")
public class Test {
    @RequestMapping("/test")
    public String test(){
        return "test";
    }
}

Configure the security settings to permit all requests for demonstration purposes and set a username/password in application.yml:

spring:
  security:
    user:
      name: ming
      password: 123456
      roles: admin

Integrating JWT with Spring Security

Dependencies for JWT and Spring Security are added:

<dependency>
  <groupId>io.jsonwebtoken</groupId>
  <artifactId>jjwt</artifactId>
  <version>0.9.1</version>
</dependency>

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-security</artifactId>
  <version>2.3.1.RELEASE</version>
</dependency>

Key classes:

JwtUser : implements UserDetails and holds username, password, state, and authorities.

JwtTokenUtil : creates, parses, validates, and refreshes JWT tokens using a secret and expiration time.

JwtAuthenticationTokenFilter : extracts the token from the request header, validates it, and sets the authentication in the security context.

JwtUserDetailsServiceImpl : loads a user from the database and converts roles to SimpleGrantedAuthority objects.

UserServiceImpl : authenticates a user, generates a token via JwtTokenUtil, and returns it in a RetResult.

Security configuration registers the filter before UsernamePasswordAuthenticationFilter and defines URL rules (e.g., permitting /auth/** and requiring authentication for others).

JSON‑Based Login

A custom filter CustomAuthenticationFilter overrides attemptAuthentication to read JSON payloads (username and password) using Jackson. The filter is registered in the security config, replacing the default filter and mapping to /login/self. Success and failure handlers return appropriate responses.

Password Encryption

A BCryptPasswordEncoder bean is defined and injected into service layers. When creating or updating a user, the password is encoded with bCryptPasswordEncoder.encode(). During login, bCryptPasswordEncoder.matches() verifies the raw password against the stored hash.

Database Authentication

The article shows how to configure UserDetailsService to fetch users from a database, set up role‑based URL protection (e.g., .antMatchers("/admin/**").hasRole("admin")), and use formLogin() with a custom login processing URL.

Data Model Design

A simple ER diagram is presented for users, roles, and permissions, illustrating the many‑to‑many relationship and how roles are linked to permissions.

Final Remarks

The guide emphasizes the end‑to‑end process of configuring RBAC in a Spring Boot application, from basic in‑memory security to full JWT‑based stateless authentication, JSON login handling, and secure password storage.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaSpring BootAuthenticationJWTRBACRole-Based Access ControlSpring Security
Architect's Guide
Written by

Architect's Guide

Dedicated to sharing programmer-architect skills—Java backend, system, microservice, and distributed architectures—to help you become a senior architect.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.