Below is a complete, enterprise-grade roadmap for implementing Role-Based Access Control (RBAC) in a Spring Boot microservices system (Auth service + Gateway + downstream services). Itโ€™s practical, scalable, and production-ready.


๐Ÿš€ Enterprise RBAC Roadmap (Spring Boot)

๐Ÿงญ Phase 0 โ€” Define Your Authorization Model

Decide early:

โœ” Core concepts

  • User โ†’ system identity
  • Role โ†’ group of permissions (ADMIN, USER, MANAGER)
  • Permission (Authority) โ†’ fine-grained action (READ_USER, CREATE_ORDER, etc.)
  • Tenant (optional) โ†’ for multi-tenant systems

โœ” Naming convention (very important)

ROLE_ADMIN
ROLE_MANAGER
ROLE_USER

PERM_USER_READ
PERM_USER_WRITE
PERM_REPORT_VIEW
PERM_REPORT_EXPORT

๐Ÿ— Phase 1 โ€” Database Design (JPA Entities)

๐Ÿงฉ Tables

users
roles
permissions
user_roles
role_permissions

๐Ÿ“ฆ Entity Model

User

@Entity
@Table(name = "users")
public class User {
    @Id
    private Long id;

    private String username;
    private String password;
    private String tenantId;

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "user_roles")
    private Set<Role> roles;
}

Role

@Entity
@Table(name = "roles")
public class Role {
    @Id
    private Long id;

    private String name; // ROLE_ADMIN

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "role_permissions")
    private Set<Permission> permissions;
}

Permission

@Entity
@Table(name = "permissions")
public class Permission {
    @Id
    private Long id;

    private String name; // PERM_USER_READ
}

๐Ÿ” Phase 2 โ€” JWT Design (Auth Service)

Token should contain:

{
  "sub": "akshay",
  "tenantId": "T1",
  "roles": ["ADMIN"],
  "permissions": ["PERM_USER_READ","PERM_USER_WRITE"]
}

Token creation

Jwts.builder()
    .setSubject(username)
    .claim("tenantId", tenantId)
    .claim("roles", roles)
    .claim("permissions", permissions)
    .signWith(key)
    .compact();

๐Ÿ”Ž Phase 3 โ€” JWT Parsing (Resource Services)

Inside your JWT filter:

Claims claims = jwtUtil.extractClaims(token);

String username = claims.getSubject();
String tenantId = claims.get("tenantId", String.class);

List<String> roles = claims.get("roles", List.class);
List<String> permissions = claims.get("permissions", List.class);

List<GrantedAuthority> authorities = new ArrayList<>();

roles.forEach(r -> authorities.add(new SimpleGrantedAuthority("ROLE_" + r)));
permissions.forEach(p -> authorities.add(new SimpleGrantedAuthority(p)));

UsernamePasswordAuthenticationToken auth =
        new UsernamePasswordAuthenticationToken(username, null, authorities);

auth.setDetails(tenantId);

SecurityContextHolder.getContext().setAuthentication(auth);

๐Ÿ›ก Phase 4 โ€” Security Configuration

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {

    http.csrf(csrf -> csrf.disable())
        .authorizeHttpRequests(auth -> auth

            .requestMatchers("/auth/**").permitAll()

            .requestMatchers("/api/admin/**").hasRole("ADMIN")

            .requestMatchers("/api/users/**")
                .hasAnyRole("USER","ADMIN")

            .requestMatchers("/api/reports/**")
                .hasAuthority("PERM_REPORT_VIEW")

            .anyRequest().authenticated()
        )
        .sessionManagement(s -> 
            s.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        );

    return http.build();
}

๐Ÿง  Phase 5 โ€” Method-Level Authorization

Enable:

@EnableMethodSecurity

Use in service/controller:

@PreAuthorize("hasRole('ADMIN')")
public void deleteUser() {}

@PreAuthorize("hasAuthority('PERM_USER_WRITE')")
public void updateUser() {}

@PreAuthorize("#tenantId == authentication.details")
public void accessTenantData(String tenantId) {}

๐Ÿงฉ Phase 6 โ€” Multi-Tenant RBAC

Store tenantId in:

  • JWT claim
  • Database user table

Then validate:

@PreAuthorize("#tenantId == authentication.details")

OR create TenantContext (ThreadLocal)


๐ŸŒ Phase 7 โ€” API Gateway Security (Recommended)

In gateway:

โœ” Validate JWT
โœ” Extract roles
โœ” Forward headers:

X-User
X-Roles
X-Tenant

Downstream services:

  • trust gateway
  • no need to parse JWT again (optional optimization)

๐Ÿ”„ Phase 8 โ€” Role Management APIs

Create admin APIs:

POST /roles
POST /permissions
POST /roles/{id}/permissions
POST /users/{id}/roles

๐Ÿงช Phase 9 โ€” Testing Strategy

โœ” Unit tests

  • JWT parsing
  • permission mapping

โœ” Integration tests

  • endpoint access with roles

โœ” Security tests

  • invalid token
  • missing roles
  • tenant mismatch

๐Ÿ“Š Phase 10 โ€” Auditing & Logging

Store logs:

userId
role
action
endpoint
timestamp
tenantId

Use tools like:

  • ELK stack
  • Grafana Loki

๐Ÿงฏ Phase 11 โ€” Production Hardening

โœ” Use RSA instead of shared secret

  • Auth service signs with private key
  • services verify using public key

โœ” Token expiry

access token โ†’ 15 min
refresh token โ†’ 7 days

โœ” Rate limiting

At Gateway level


๐Ÿ“ฆ Phase 12 โ€” Folder Structure

security/
  JwtUtil
  JwtAuthenticationFilter
  SecurityConfig
  CustomUserDetails

auth/
  AuthController
  TokenService

rbac/
  RoleService
  PermissionService

๐Ÿ† Final Enterprise Architecture

Client
   โ†“
API Gateway (JWT validation, rate limit)
   โ†“
User Service (RBAC enforcement)
   โ†“
Database

๐ŸŽฏ Enterprise Best Practices Checklist

โœ” Use roles + permissions together
โœ” Store authorities in JWT
โœ” Use @PreAuthorize for business logic
โœ” Use stateless authentication
โœ” Use RSA keys (no shared secrets)
โœ” Implement multi-tenant isolation
โœ” Log every sensitive action
โœ” Centralize auth in Auth Service


Read other awesome articles inย Medium.com or in akcoding’s posts.

OR

Join us on YouTube Channel

OR Scan the QR Code to Directly open the Channel ๐Ÿ‘‰

AK Coding YouTube Channel

Share with