If you need to secure REST endpoints based on user roles, what Spring Security configurations would you use?

Securing REST endpoints by role in Spring Security means declaring authorization rules on the HttpSecurity chain that tie specific URL patterns to required roles or authorities, so unauthorized requests are rejected before reaching the controller.

Key Points: • authorizeHttpRequests() is the modern entry point for defining request-level rules (replacing the older authorizeRequests()). • requestMatchers(...).hasRole("X") checks for a role, while hasAuthority("X") checks a raw authority string without the ROLE_ prefix assumption. • Multiple roles can be permitted with hasAnyRole("A", "B"). • Combine with .oauth2ResourceServer(...) if roles come from JWT claims rather than a local user store. • Fallback rules like anyRequest().authenticated() ensure nothing is left unintentionally open.

Example: A REST API secures /api/orders/** so only users with ROLE_MANAGER can create or delete orders, while any authenticated user can view them via a separate, less restrictive rule.

Code Example:

http.authorizeHttpRequests(auth -> auth
    .requestMatchers(HttpMethod.GET, "/api/orders/**").authenticated()
    .requestMatchers(HttpMethod.POST, "/api/orders/**").hasRole("MANAGER")
    .anyRequest().denyAll());

Interview Tip: A concise interview answer is:

"I'd use authorizeHttpRequests() in the SecurityFilterChain, chaining requestMatchers() with hasRole() or hasAuthority() checks per endpoint and HTTP method. That gives fine-grained, declarative control over exactly which roles can hit which REST operations."