In your application, there are two types of users: ADMIN and USER. Each type should have access to different sets of API endpoints. Explain how you would configure Spring Security to enforce these access controls based on the user's role.

Enforcing per-role access to different URL namespaces is done by defining path-based authorization rules that map URL prefixes to required roles in the SecurityFilterChain, so requests are matched against the most specific applicable pattern.

Key Points: • requestMatchers("/admin/**").hasRole("ADMIN") restricts everything under /admin to admin users only. • requestMatchers("/user/**").hasAnyRole("USER", "ADMIN") can allow broader access where appropriate. • Rules are evaluated in order, so more specific patterns should be declared before general catch-alls like anyRequest().authenticated(). • Roles come from the user's GrantedAuthority set, typically loaded from a database via UserDetailsService. • A user without the required role hitting a restricted path receives a 403 Forbidden rather than a login prompt.

Example: An ADMIN can reach both /admin/reports and /user/profile, while a USER hitting /admin/reports gets rejected with 403 because the rule requires ROLE_ADMIN specifically.

Code Example:

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

Interview Tip: A concise interview answer is:

"I'd map URL prefixes to required roles in the SecurityFilterChain, like restricting /admin/** to hasRole('ADMIN') and /user/** to any authenticated user with USER or ADMIN. Ordering matters—specific patterns need to come before general ones—so each request is matched against the right rule."