Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 39 ยท Filter Chain and Configuration

Exception Handling: Entry Points and Access Denied

Understand ExceptionTranslationFilter, the difference between 401 and 403, and write a custom AuthenticationEntryPoint and AccessDeniedHandler returning JSON.

When a request is refused, the client needs an answer it can use. A browser should be sent to the login page. A mobile app should get 401 with a JSON body. A logged-in user who tries an admin page should see 403, not a login form again. Spring Security produces these different answers through two small extension points: the AuthenticationEntryPoint and the AccessDeniedHandler. This lesson explains who calls them and how to customize both.

As in the rest of this track, the real Spring classes are shown read-only; the runnable examples are Java stand-ins for the decision logic.

Two failures, two meanings

Situation Exception Default answer HTTP status
The caller is anonymous and the URL needs a login AuthenticationException (raised via AccessDeniedException for an anonymous user) The entry point starts authentication 401, or a 302 redirect to /login
The caller is known but lacks permission AccessDeniedException The access-denied handler 403

The names of the statuses are misleading: 401 is called "Unauthorized" but means unauthenticated ("I do not know who you are"), while 403 "Forbidden" means "I know who you are and the answer is no". Sending the right one matters to clients, which retry with credentials after a 401 but not after a 403.

Who calls the handlers

The ExceptionTranslationFilter sits just before AuthorizationFilter in the chain (see the filter chain). It wraps the rest of the chain in a try/catch:

flowchart TD
    A["ExceptionTranslationFilter"] --> B["chain.doFilter(...)"]
    B --> C["AuthorizationFilter"]
    C -->|"AccessDeniedException"| D{"Is the user anonymous?"}
    D -->|"yes"| E["AuthenticationEntryPoint<br/>(401 or redirect to login)"]
    D -->|"no"| F["AccessDeniedHandler<br/>(403)"]
    C -->|"AuthenticationException"| E

The filter decides by looking at the current authentication: anonymous leads to the entry point, a real user to the access-denied handler.

This is why exceptions thrown in your controller are not handled by this filter in the same way as a @ControllerAdvice: a @PreAuthorize failure inside MVC throws AccessDeniedException that propagates out of the dispatcher and is caught here, unless an @ExceptionHandler catches it first. Watch for a broad @ExceptionHandler(Exception.class) in your advice: it will swallow AccessDeniedException and turn every denial into a 500.

Configuring both handlers

Java
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
    http
        .securityMatcher("/api/**")
        .authorizeHttpRequests(a -> a.anyRequest().authenticated())
        .exceptionHandling(e -> e
            .authenticationEntryPoint(new JsonEntryPoint())
            .accessDeniedHandler(new JsonAccessDeniedHandler()));
    return http.build();
}

Both are one-method interfaces:

Java
class JsonEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest req, HttpServletResponse res,
                         AuthenticationException ex) throws IOException {
        res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        res.setContentType("application/json");
        res.setHeader("WWW-Authenticate", "Bearer");
        res.getWriter().write("{\"error\":\"unauthenticated\"}");
    }
}

class JsonAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest req, HttpServletResponse res,
                       AccessDeniedException ex) throws IOException {
        res.setStatus(HttpServletResponse.SC_FORBIDDEN);
        res.setContentType("application/json");
        res.getWriter().write("{\"error\":\"forbidden\"}");
    }
}

Keep the messages generic. "User alice lacks ROLE_ADMIN" tells an attacker which accounts and roles exist. Log the detail on the server instead.

The WWW-Authenticate header is part of the HTTP protocol: a 401 must say which scheme is acceptable (Basic realm="...", Bearer). Spring's built-in BasicAuthenticationEntryPoint and the bearer-token entry point set it for you.

Built-in entry points worth knowing

Class Behavior
LoginUrlAuthenticationEntryPoint Redirects to the login page (used by formLogin)
BasicAuthenticationEntryPoint 401 plus WWW-Authenticate: Basic
HttpStatusEntryPoint Only a status code, no body
BearerTokenAuthenticationEntryPoint 401 plus WWW-Authenticate: Bearer (resource server)
DelegatingAuthenticationEntryPoint Picks one of several entry points by request matcher

When you configure several login mechanisms at once, Spring Security uses the first declared one as the default entry point. DelegatingAuthenticationEntryPoint lets one chain serve both worlds: browser requests (Accept: text/html) get a redirect, everything else gets 401.

A runnable model of the decision

The stand-in below reproduces the filter's decision and a content-negotiating delegating entry point.

Java ExceptionTranslationFilter decision model (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice the second line of results: the same URL gives a browser a redirect and an API client a 401. That is exactly what you want from a combined application.

Avoiding information leaks: 404 instead of 403

Sometimes even the existence of a resource is secret. For GET /orders/42 where order 42 belongs to someone else, a 403 confirms that the order exists. Many teams return 404 in that case. Implement it in the service or repository layer (look up the order by id and owner, so another user's order is simply "not found") rather than in the handler. The next lessons on method security show how to put that check next to the data.

Testing your handlers

A tiny JSON writer is easy to get wrong (content type, status, character encoding), so test the behavior, not the class. With MockMvc (see testing secured endpoints):

Java
mockMvc.perform(get("/api/orders"))
       .andExpect(status().isUnauthorized())
       .andExpect(header().string("WWW-Authenticate", "Bearer"));

mockMvc.perform(get("/api/admin").with(user("bob").roles("USER")))
       .andExpect(status().isForbidden());

Here is a second runnable model: it serializes error bodies safely. A hand-built JSON string breaks as soon as a message contains a quote, so the helper escapes it.

Java Writing a safe JSON error body (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Common mistakes

  • Using sendError and getting an HTML error page. response.sendError(401) hands control to the servlet container's error dispatch, which may render an HTML page or loop through your security chain again. Write the status and body directly when you want JSON.
  • A catch-all @ExceptionHandler. It turns denials into 500. Rethrow AccessDeniedException and AuthenticationException.
  • A redirect for API clients. 302 to /login makes a JavaScript fetch receive the login HTML with status 200. Use 401 for API chains.
  • Leaking detail. Keep messages generic and log specifics.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. An authenticated user without the required role requests /admin. What does Spring Security do by default?

    The user is known, so this is an authorization failure, handled by the AccessDeniedHandler with 403.
  2. 2. Which component decides between the entry point and the access-denied handler?

    ExceptionTranslationFilter catches the security exceptions and checks whether the current user is anonymous.
  3. 3. What must a 401 response from an API include according to HTTP?

    A 401 challenge names the authentication scheme, for example Basic or Bearer.
  4. 4. Why can a broad @ExceptionHandler(Exception.class) in a @ControllerAdvice break security responses?

    MVC handlers run first for exceptions thrown from controller methods, so a catch-all hides denials from ExceptionTranslationFilter.

Summary

  • 401 means unauthenticated (use the entry point); 403 means authenticated but not allowed (use the access-denied handler).
  • ExceptionTranslationFilter makes the choice by checking whether the current user is anonymous.
  • Configure both with http.exceptionHandling(...); write JSON for API chains and redirect only browsers.
  • Always send WWW-Authenticate with a 401, and keep error bodies generic.
  • Beware catch-all @ExceptionHandler methods and sendError.

Next: Form login and logout