When a user tries to access a resource without the necessary permissions, you want to redirect them to a custom "access denied" page instead of displaying the default Spring Security error message. How would you achieve this in your Spring Security configuration?

Redirecting unauthorized users to a custom page instead of Spring Security's default error is done by supplying a custom AccessDeniedHandler, which intercepts the AccessDeniedException thrown when an authenticated user lacks the required permissions.

Key Points: • AccessDeniedHandler is distinct from AuthenticationEntryPoint—the former handles authenticated-but-unauthorized users, the latter handles unauthenticated ones. • You register the custom handler via .exceptionHandling(ex -> ex.accessDeniedHandler(...)) in the SecurityFilterChain. • The handler can redirect to a static page or render a custom response with tailored messaging. • Logging the denial (user, resource, timestamp) inside the handler is useful for auditing suspicious access attempts. • This customization improves user experience without weakening the actual authorization check that triggered it.

Example: A user without the ADMIN role hitting /admin/dashboard triggers AccessDeniedException, and the custom handler redirects them to /access-denied with a friendly explanation instead of Spring's generic 403 whitelabel page.

Code Example:

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http.exceptionHandling(ex -> ex
        .accessDeniedHandler((request, response, accessDeniedException) ->
            response.sendRedirect("/access-denied")));
    return http.build();
}

Interview Tip: A concise interview answer is:

"I'd implement a custom AccessDeniedHandler and register it through exceptionHandling().accessDeniedHandler() in the security configuration. It intercepts the AccessDeniedException thrown for authenticated-but-unauthorized users and redirects them to a friendly custom page instead of Spring's default error response."