DEV Community

Rajesh Mishra
Rajesh Mishra

Posted on Originally published at howtostartprogramming.in

Spring Security role based access control RBAC tutorial — Complete Guide

Spring Security role based access control RBAC tutorial — Complete Guide

A practical, in-depth guide to Spring Security role based access control RBAC tutorial with examples.

INTRO

Most Spring Boot applications ship with a default security configuration that either leaves every endpoint open or locks everything behind a generic login. In real‑world services, you rarely have a single “admin” role that can do everything; you need fine‑grained permissions that map to business concepts like MANAGER, CUSTOMER_SUPPORT, or API_CONSUMER. Without a clear RBAC strategy, you end up scattering if checks throughout controllers, duplicating logic, and exposing sensitive data when a role is added or changed.

Spring Security gives you the building blocks—GrantedAuthority, @PreAuthorize, and the HttpSecurity DSL—but stitching them together into a maintainable RBAC layer is non‑trivial. You have to decide where roles live (in the database, LDAP, or JWT claims), how they are loaded into the security context, and how to enforce them consistently across REST endpoints and method calls. The guide linked below walks through every decision point, shows you how to avoid common pitfalls, and ends with a production‑ready configuration you can drop into any Spring Boot project.

WHAT YOU'LL LEARN

  • How to model roles and permissions in a relational database and map them to Spring Security’s GrantedAuthority.
  • Configuring UserDetailsService to load a user’s authorities efficiently with JPA/Hibernate.
  • Securing REST endpoints with both URL‑based rules (http.authorizeRequests()) and method‑level annotations (@PreAuthorize).
  • Dynamically updating a user’s roles at runtime without restarting the application.
  • Testing RBAC policies using Spring’s @WithMockUser and MockMvc.
  • Pitfalls to watch out for: role hierarchy, authority duplication, and caching stale permissions.

A SHORT CODE SNIPPET

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private CustomUserDetailsService userDetailsService;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService)
.passwordEncoder(new BCryptPasswordEncoder());
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/api/public/**").permitAll()
.antMatchers(HttpMethod.GET, "/api/orders/**").hasAnyRole("USER", "ADMIN")
.antMatchers(HttpMethod.POST, "/api/orders/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.httpBasic();
}
}
Enter fullscreen mode Exit fullscreen mode

The snippet shows a concise, production‑oriented security filter chain: public endpoints are open, read‑only order APIs accept both USER and ADMIN, while creation requires ADMIN. The heavy lifting—loading roles from the database—is delegated to CustomUserDetailsService.

KEY TAKEAWAYS

  • Define roles and permissions as first‑class entities; never hard‑code strings throughout your codebase.
  • Leverage both URL‑level and method‑level security to keep the access matrix readable and testable.
  • Keep the authority cache in sync with the data store; a simple @CacheEvict on role updates prevents stale permissions.
  • Comprehensive unit and integration tests are essential; they catch mis‑configured antMatchers before they hit production.

👉 Read the complete guide with step-by-step examples, common mistakes, and production tips:

Spring Security role based access control RBAC tutorial — Complete Guide

Top comments (0)