You are developing a web application where users can have different roles (e.g., ADMIN, USER). How would you implement role-based access control using Spring Security to ensure that only users with the ADMIN role can access certain endpoints?

Role-based access control restricts specific endpoints to users holding a given role, implemented in Spring Security by mapping URL patterns or methods to required authorities and rejecting requests that don't match.

Key Points: • Roles are assigned to users (e.g., ADMIN, USER) and exposed as GrantedAuthority values in the Authentication object. • URL-based rules use .requestMatchers("/admin/**").hasRole("ADMIN") in the SecurityFilterChain. • Method-level rules use @PreAuthorize("hasRole('ADMIN')") for finer control on individual service methods. • hasRole() automatically expects a "ROLE_" prefix internally, while hasAuthority() checks the raw authority string. • Combining URL-level and method-level checks gives layered protection—coarse at the boundary, precise at the business logic.

Example: Only users with ROLE_ADMIN can reach /admin/users, while any authenticated user can reach /profile; a regular USER hitting /admin/users gets a 403 Forbidden.

Code Example:

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http.authorizeHttpRequests(auth -> auth
            .requestMatchers("/admin/**").hasRole("ADMIN")
            .requestMatchers("/user/**").hasAnyRole("ADMIN", "USER")
            .anyRequest().authenticated())
        .formLogin(Customizer.withDefaults());
    return http.build();
}

Interview Tip: A concise interview answer is:

"I'd configure the SecurityFilterChain with requestMatchers mapping URL patterns to required roles, like restricting /admin/** to hasRole('ADMIN'). For finer-grained control I'd also add @PreAuthorize on individual service methods, so access is enforced both at the endpoint boundary and inside business logic."