Table of Contents
- What is RBAC?
- Benefits of Using RBAC
- Defining Roles in Spring Security
- Role-Based Access with Annotations
- Role Hierarchy in Spring Security
- Fine-Grained Access Control Using Expressions
- Best Practices for Implementing RBAC
- Summary
1. What is RBAC?
Role-Based Access Control (RBAC) is a security mechanism that restricts access to resources based on the roles assigned to users. In Spring Security, roles determine what actions a user can perform or what endpoints they can access.
Example:
- Role
ADMIN
may access/admin/**
- Role
USER
may only access/user/**
2. Benefits of Using RBAC
- Centralized control: Easier management of access rules.
- Scalability: Adding new roles or users doesn’t require changing application logic.
- Improved security: Reduces chances of unauthorized access.
- Auditable: Easier to audit and enforce organizational security policies.
3. Defining Roles in Spring Security
Step 1: User Definition with Roles
javaCopyEdit@Bean
public InMemoryUserDetailsManager userDetailsService() {
UserDetails user = User.withUsername("user")
.password(passwordEncoder().encode("user123"))
.roles("USER")
.build();
UserDetails admin = User.withUsername("admin")
.password(passwordEncoder().encode("admin123"))
.roles("ADMIN")
.build();
return new InMemoryUserDetailsManager(user, admin);
}
Spring automatically prefixes ROLE_
to each role. So roles("ADMIN")
becomes ROLE_ADMIN
.
4. Role-Based Access with Annotations
@PreAuthorize and @Secured
Using @Secured
:
javaCopyEdit@Secured("ROLE_ADMIN")
@GetMapping("/admin/dashboard")
public String adminDashboard() {
return "Welcome Admin!";
}
Using @PreAuthorize
:
javaCopyEdit@PreAuthorize("hasRole('ADMIN')")
@GetMapping("/admin/dashboard")
public String adminDashboard() {
return "Welcome Admin!";
}
To enable annotations:
javaCopyEdit@EnableMethodSecurity(securedEnabled = true, prePostEnabled = true)
@Configuration
public class SecurityConfig {
// your security beans
}
5. Role Hierarchy in Spring Security
You can define role inheritance so that a higher role includes the authorities of lower roles.
javaCopyEdit@Bean
public RoleHierarchy roleHierarchy() {
RoleHierarchyImpl hierarchy = new RoleHierarchyImpl();
hierarchy.setHierarchy("ROLE_ADMIN > ROLE_USER");
return hierarchy;
}
This means an ADMIN
implicitly has all permissions of a USER
.
6. Fine-Grained Access Control Using Expressions
Spring Security provides rich expression support with @PreAuthorize
and @PostAuthorize
.
Examples:
javaCopyEdit@PreAuthorize("hasRole('ADMIN') or hasRole('MODERATOR')")
public String accessControl() {
return "Admin or Moderator Access";
}
@PreAuthorize("#user.username == authentication.name")
public String getUserData(User user) {
return "Accessing own data";
}
You can access:
authentication
: the current authentication objectprincipal
: the current logged-in user#param
: method parameters
7. Best Practices for Implementing RBAC
- Use meaningful role names (
ROLE_VIEWER
,ROLE_MANAGER
) over generic ones. - Externalize role definitions if possible (e.g., in DB or LDAP).
- Use role hierarchy to simplify rules.
- Apply the principle of least privilege—grant only necessary permissions.
- Regularly audit roles and access mappings.
8. Summary
RBAC is a powerful and scalable way to manage access control in Spring applications. It lets you separate who can access what, based on roles rather than hard-coded user IDs.
Key Concepts Covered:
- Defining users with roles
- Using
@Secured
,@PreAuthorize
for enforcement - Configuring role hierarchies
- Using security expressions for dynamic control
Next, we’ll explore more advanced topics like JWT-based authentication, OAuth2, and custom authorization filters for building highly secure RESTful applications.