Category: spring_boot
Role-Based Access Co
Published on 26 Jun 2026
Explanation
Role-Based Access Control (RBAC) is an
authorization mechanism that
restricts access to
resources based on user roles. Common
roles include ADMIN, USER, and MANAGER.
After authentication,
Spring Security checks whether
the authenticated user
has the required
role before granting access.
Code:
Roles: ADMIN USER MANAGER
Explanation
Users are assigned one or more
roles. These roles determine which API
endpoints they can access. In Spring
Security, roles are usually loaded through
a UserDetailsService.
@Bean
public UserDetailsService
userDetailsService() {
UserDetails admin = User.builder()
.username("admin")
.password(passwordEncoder().encode
}
Code:
UserDetails user = User.builder()
.username("user")
.password(passwordEncoder().encode(
"user123"))
.roles("USER")
.build();
return new InMemoryUserDetailsManager(
admin, user);
}
Explanation
Spring Security can restrict access to
endpoints using request matchers. Only users
with the required role can access
the corresponding API.
@Bean
public SecurityFilterChain
securityFilterChain(HttpSecurity http)
throws Exception {
}
Code:
http
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(
auth -> auth
.requestMatchers(
"/admin/**").hasRole("ADMIN")
.requestMatchers(
"/user/**").hasAnyRole("USER", "ADMIN")
.anyRequest().authenticated()
)
.httpBasic();
return http.build();
}
Explanation
Method-level security provides
fine-grained access control.
The @PreAuthorize annotation
allows role checks
directly on controller or service methods.
Code:
@RestController
@RequestMapping("/reports")
public class ReportController {
@GetMapping
@PreAuthorize("hasRole('ADMIN')")
public String generateReport() {
return "Admin Report";
}
}
Explanation
RBAC works seamlessly with JWT
authentication.
After a user logs in, their
roles are stored inside the JWT
token and extracted during
request processing
to enforce authorization rules.
Code:
{
"sub": "admin",
"roles": ["ADMIN"]
}
Authorization: Bearer eyJhbGciOiJIUzI1NiJ9...