Back to Spring Security: JWT, OAuth2, CSRF/CORS
Q10Question 10 of 11

Custom AccessDeniedHandler and AuthenticationEntryPoint

Answer: AuthenticationEntryPoint produces the HTTP 401 response when authentication fails or is missing, and AccessDeniedHandler produces the HTTP 403 response when an authenticated user lacks permission; both must be customized for REST APIs to return JSON instead of HTML.

Key Concepts
  • AuthenticationEntryPoint handles HTTP 401 responses when authentication is missing or invalid; it is invoked when an unauthenticated user tries to access a protected resource.
  • AccessDeniedHandler handles HTTP 403 responses when an authenticated user lacks sufficient permissions for the requested operation.
  • Both are configured in SecurityFilterChain via .exceptionHandling() to return consistent JSON error responses for REST APIs.
  • Without custom handlers, Spring Security returns HTML error pages or redirects to a login page, which is inappropriate for REST APIs.
  • The handlers should return a consistent error format (status, error code, message, timestamp) without exposing internal exception details.
  • Controller-level @ExceptionHandler does NOT catch security exceptions thrown in the filter chain; you must configure these handlers in SecurityFilterChain.

Definition

AuthenticationEntryPoint produces the HTTP 401 response when authentication fails or is missing, and AccessDeniedHandler produces the HTTP 403 response when an authenticated user lacks permission; both must be customized for REST APIs to return JSON instead of HTML.
  • AuthenticationEntryPoint – invoked when a request requires authentication but the user is not authenticated; responsible for sending the 401 Unauthorized response.
  • AccessDeniedHandler – invoked when an authenticated user tries to access a resource they do not have permission for; responsible for sending the 403 Forbidden response.
  • ExceptionTranslationFilter – the Spring Security filter that catches AuthenticationException and AccessDeniedException and delegates to the appropriate handler.
  • Consistent error format – REST APIs should return the same JSON structure for all errors (status, error, message, timestamp) regardless of whether the error comes from the controller or the security filter chain.

In a bank, AuthenticationEntryPoint is like the front door guard who tells a stranger: "You cannot enter without an ID badge" (401). AccessDeniedHandler is like the vault room guard who tells an authenticated teller: "You have a valid badge, but you are not authorized to enter the vault" (403). Both guards follow the same communication protocol: they hand you a standard rejection form (JSON error response) rather than shouting at you in different formats.

Understanding the Concepts

Why do you need custom error handlers?

By default, Spring Security returns HTML error pages for 401 and 403 errors. For form-login web applications, it redirects to a login page. This is wrong for REST APIs where clients expect JSON.

Without custom handlers, a REST API client receives:

HTML
<!-- Default 403 response: useless for API clients --syn-kw">>
syn-kw"><htmlsyn-kw">>
syn-kw"><bodysyn-kw">>
syn-kw"><h1syn-kw">>Whitelabel Error Pagesyn-kw"></h1syn-kw">>
syn-kw"><psyn-kw">>Access Deniedsyn-kw"></psyn-kw">>
syn-kw"></bodysyn-kw">>
syn-kw"></htmlsyn-kw">>

With custom handlers, the client receives:

JSON
{
  "status": 403,
  "error": "FORBIDDEN",
  "message": "You do not have permission to access this resource",
  "timestamp": "2026-11-13T10:30:00Z"
}

How do you implement a custom AuthenticationEntryPoint?

AuthenticationEntryPoint handles the 401 response. It is invoked when an unauthenticated request reaches a protected endpoint.

JAVA
package com.bank.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.time.Instant;
import java.util.Map;

@Component
public class BankAuthenticationEntryPoint implements AuthenticationEntryPoint {

    private final ObjectMapper objectMapper;

    public BankAuthenticationEntryPoint(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException authException)
            throws IOException {

        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType("application/json");

        Map<String, Object> body = Map.of(
            "status", 401,
            "error", "UNAUTHORIZED",
            "message", "Authentication is required to access this resource",
            "path", request.getRequestURI(),
            "timestamp", Instant.now().toString()
        );

        objectMapper.writeValue(response.getOutputStream(), body);
    }
}

Notice the message does not include the exception's internal message. Exposing authException.getMessage() can leak information about why authentication failed (e.g., "JWT expired at 2026-11-13T10:00:00Z"), which helps attackers.

How do you implement a custom AccessDeniedHandler?

AccessDeniedHandler handles the 403 response. It is invoked when an authenticated user lacks the required role or authority.

JAVA
package com.bank.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.time.Instant;
import java.util.Map;

@Component
public class BankAccessDeniedHandler implements AccessDeniedHandler {

    private final ObjectMapper objectMapper;

    public BankAccessDeniedHandler(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public void handle(HttpServletRequest request,
                       HttpServletResponse response,
                       AccessDeniedException accessDeniedException)
            throws IOException {

        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.setContentType("application/json");

        Map<String, Object> body = Map.of(
            "status", 403,
            "error", "FORBIDDEN",
            "message", "You do not have permission to access this resource",
            "path", request.getRequestURI(),
            "timestamp", Instant.now().toString()
        );

        objectMapper.writeValue(response.getOutputStream(), body);
    }
}

How do you wire them into SecurityFilterChain?

JAVA
package com.bank.config;

import com.bank.security.BankAccessDeniedHandler;
import com.bank.security.BankAuthenticationEntryPoint;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.config.Customizer;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class BankApiSecurityConfig {

    private final BankAuthenticationEntryPoint entryPoint;
    private final BankAccessDeniedHandler accessDeniedHandler;

    public BankApiSecurityConfig(BankAuthenticationEntryPoint entryPoint,
                                 BankAccessDeniedHandler accessDeniedHandler) {
        this.entryPoint = entryPoint;
        this.accessDeniedHandler = accessDeniedHandler;
    }

    @Bean
    SecurityFilterChain apiSecurityChain(HttpSecurity http) throws Exception {
        return http
            .csrf(csrf -> csrf.disable())
            .sessionManagement(sess -> sess
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            )
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/api/public/**").permitAll()
                .requestMatchers("/api/admin/**").hasRole("ADMIN")
                .requestMatchers("/api/accounts/**").hasAuthority("ACCOUNT_READ")
                .anyRequest().authenticated()
            )
            .oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()))
            .exceptionHandling(ex -> ex
                .authenticationEntryPoint(entryPoint)
                .accessDeniedHandler(accessDeniedHandler)
            )
            .build();
    }
}

Why does @ControllerAdvice not catch security exceptions?

Spring Security filters run before the DispatcherServlet. Security exceptions (AuthenticationException, AccessDeniedException) are thrown and caught within the filter chain by ExceptionTranslationFilter. They never reach the controller layer.

JAVA
// WRONG: This will NOT catch 401/403 from Spring Security
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(AccessDeniedException.class)
    public ResponseEntity<Map<String, Object>> handleAccessDenied(
            AccessDeniedException ex) {
        // This is never invoked for security filter exceptions
        return ResponseEntity.status(403).body(Map.of("error", "forbidden"));
    }
}

There is one exception: if a controller method throws AccessDeniedException (e.g., from @PreAuthorize), Spring Security's AuthorizationFilter catches it and delegates to ExceptionTranslationFilter, which then calls the configured AccessDeniedHandler. The @ControllerAdvice still does not handle it.

What is ExceptionTranslationFilter?

ExceptionTranslationFilter is the Spring Security filter responsible for catching security exceptions and delegating to the right handler:

ExceptionHandler calledTypical response
AuthenticationExceptionAuthenticationEntryPointHTTP 401
AccessDeniedException (authenticated user)AccessDeniedHandlerHTTP 403
AccessDeniedException (anonymous user)AuthenticationEntryPointHTTP 401

Notice the third row: if an anonymous (unauthenticated) user triggers an AccessDeniedException, ExceptionTranslationFilter treats it as an authentication problem and calls the AuthenticationEntryPoint, not the AccessDeniedHandler.

What are common mistakes?

1. Exposing internal exception messages:

JAVA
// WRONG: Leaks internal information
Map<String, Object> body = Map.of(
    "message", authException.getMessage()  // "Full authentication is required"
);

// CORRECT: Use a generic message
Map<String, Object> body = Map.of(
    "message", "Authentication is required to access this resource"
);

2. Forgetting to set Content-Type:

JAVA
// WRONG: No Content-Type header
// Client may interpret the response as HTML
response.getWriter().write("{\"error\":\"unauthorized\"}");

// CORRECT: Set Content-Type to JSON
response.setContentType("application/json");
objectMapper.writeValue(response.getOutputStream(), body);

How do you add audit logging?

In a banking application, failed authentication and authorization attempts must be logged for compliance:

JAVA
@Override
public void commence(HttpServletRequest request,
                     HttpServletResponse response,
                     AuthenticationException authException)
        throws IOException {

    logger.warn("Authentication failed for URI={} from IP={}",
        request.getRequestURI(),
        request.getRemoteAddr());

    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    response.setContentType("application/json");
    objectMapper.writeValue(response.getOutputStream(), errorBody(request, 401));
}

Log the URI and client IP, but never log the submitted credentials or bearer token.

What should a senior engineer know?

  • For OAuth2 resource servers, Spring Security provides BearerTokenAuthenticationEntryPoint and BearerTokenAccessDeniedHandler that return RFC 6750 compliant responses with WWW-Authenticate headers.
  • You can configure different handlers for different SecurityFilterChain beans. The API chain returns JSON; the admin portal chain redirects to a login page.
  • In reactive applications (WebFlux), the equivalents are ServerAuthenticationEntryPoint and ServerAccessDeniedHandler.
  • Rate-limit failed authentication attempts at the entry point level to slow down brute-force attacks.

Visual Overview

DIAGRAM
┌─────────────────────────────────────────────────┐
│  HTTP Request: GET /api/accounts/SAV2001         │
│  (no Authorization header)                       │
└──────────────────────┬──────────────────────────┘
                       │
                       ▼
┌─────────────────────────────────────────────────┐
│  SecurityFilterChain filters                     │
│  BearerTokenAuthenticationFilter: no token found │
└──────────────────────┬──────────────────────────┘
                       │
                       ▼
┌─────────────────────────────────────────────────┐
│  AuthorizationFilter                             │
│  anyRequest().authenticated() → NOT authenticated│
│  Throws AccessDeniedException                    │
└──────────────────────┬──────────────────────────┘
                       │
                       ▼
┌─────────────────────────────────────────────────┐
│  ExceptionTranslationFilter                      │
│  User is anonymous → treats as auth problem      │
│  Delegates to AuthenticationEntryPoint           │
└──────────────────────┬──────────────────────────┘
                       │
                       ▼
┌─────────────────────────────────────────────────┐
│  BankAuthenticationEntryPoint                    │
│  Returns: 401 JSON                               │
│  { status: 401, error: "UNAUTHORIZED", ... }     │
└─────────────────────────────────────────────────┘

Key Takeaway

REST APIs need consistent JSON error responses for authentication and authorization failures. Without custom handlers, Spring Security returns HTML error pages or redirects, which breaks API clients that expect JSON.

AuthenticationEntryPoint handles the 401 case: the user is not authenticated. AccessDeniedHandler handles the 403 case: the user is authenticated but lacks permission. Both are wired into SecurityFilterChain through the exceptionHandling() configuration.

The important detail that catches many developers off guard is that @ControllerAdvice and @ExceptionHandler do not catch security exceptions. Security filters run before the DispatcherServlet, so exceptions thrown in the filter chain are caught by ExceptionTranslationFilter and routed to the configured handlers. This is why you must configure these handlers in SecurityFilterChain rather than relying on controller-level exception handling.

In a banking application, Rajesh configures both handlers to return a standardized error body with status code, error type, generic message, request path, and timestamp. The handlers never expose internal exception messages, which could reveal whether a username exists, why a JWT was rejected, or what authorization rule failed. For compliance, the handlers log the failed attempt with the request URI and client IP, but never log credentials or tokens.

The one sentence to remember: AuthenticationEntryPoint returns 401 for unauthenticated requests and AccessDeniedHandler returns 403 for unauthorized requests, and both must be configured in SecurityFilterChain because @ControllerAdvice cannot catch security filter exceptions.

---

Share
Use ← → arrow keys to navigate