Hackforge Academy

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...

๐Ÿš€ Learn Spring Boot with real-world projects

๐Ÿ’ก Build REST APIs step by step

๐Ÿง  Improve backend development skills

๐ŸŽฏ Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

๐Ÿ

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
โš›๏ธ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
โ˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community