0Pricing
Spring Security 6 & JWT Authentication · Lesson

Handling Authentication Errors and Entry Points

Customize how your JWT-secured Spring app responds to missing, invalid, or expired tokens using AuthenticationEntryPoint and AccessDeniedHandler.

Handling Authentication Errors and Entry Points is a free Spring Security 6 & JWT Authentication lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Spring Security 6 & JWT Authentication learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Two Kinds of Security Failure

Spring Security distinguishes two failures:

  • Authentication failure (401): the user is not identified — missing or bad token
  • Authorization failure (403): the user is known but lacks permission

Each is handled by a different component.

The Default Behavior

Out of the box, a JWT app without a custom handler may redirect to a login page or return an HTML error. For a stateless API you usually want a clean JSON 401 instead.

AuthenticationEntryPoint

The AuthenticationEntryPoint is invoked when an unauthenticated user hits a protected endpoint. Implement commence to write your own response.

public interface AuthenticationEntryPoint {
    void commence(HttpServletRequest req,
                  HttpServletResponse res,
                  AuthenticationException ex);
}

Returning a JSON 401

Here the entry point sets a 401 status and writes a small JSON body, ideal for SPA and mobile clients.

res.setStatus(401);
res.setContentType('application/json');
res.getWriter().write("{\"error\":\"Unauthorized\"}");

AccessDeniedHandler

When an authenticated user lacks the required role, the AccessDeniedHandler runs. Implement handle to send a 403 response.

public interface AccessDeniedHandler {
    void handle(HttpServletRequest req,
                HttpServletResponse res,
                AccessDeniedException ex);
}

Returning a JSON 403

The denied handler mirrors the entry point but uses status 403 to signal a permission problem rather than a missing identity.

res.setStatus(403);
res.setContentType('application/json');
res.getWriter().write("{\"error\":\"Forbidden\"}");

Wiring Handlers into HttpSecurity

Register both handlers in your security configuration through exceptionHandling.

http.exceptionHandling(ex -> ex
    .authenticationEntryPoint(jwtEntryPoint)
    .accessDeniedHandler(jwtDeniedHandler));

Errors Inside the JWT Filter

If your JWT filter detects an expired or malformed token, do not throw a raw exception. Instead set a request attribute and let the entry point produce a consistent response.

catch (ExpiredJwtException e) {
    request.setAttribute('jwt_error', 'expired');
    filterChain.doFilter(request, response);
}

Including Helpful Details

A good error body helps clients react. Include a machine-readable code and a timestamp, but never leak internal stack traces or secrets.

res.getWriter().write(
  "{\"error\":\"token_expired\",\"status\":401}");

Consistent Error Shape

Keep every security error in the same JSON shape as your other API errors. Consistency lets the frontend handle 401, 403, and 500 with one error pipeline.

Testing the Handlers

Use MockMvc to confirm an unauthenticated request returns 401 and an under-privileged request returns 403 with the expected JSON.

mockMvc.perform(get('/api/secure'))
    .andExpect(status().isUnauthorized())
    .andExpect(jsonPath('$.error').value('Unauthorized'));

Quick Check

Test your understanding of security error handling.

Recap

You learned to customize JWT security errors:

  • AuthenticationEntryPoint handles 401 (unauthenticated)
  • AccessDeniedHandler handles 403 (forbidden)
  • Wire both via exceptionHandling
  • Return consistent JSON and never leak internals

Clear, predictable error responses make your secured API far easier to consume.

Frequently asked questions

Is the “Handling Authentication Errors and Entry Points” lesson free?

Yes — the full text of “Handling Authentication Errors and Entry Points” is free to read here on the web, and the Spring Security 6 & JWT Authentication course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Spring Security 6 & JWT Authentication course, upgrade to CoddyKit PRO.

What will I learn in “Handling Authentication Errors and Entry Points”?

Customize how your JWT-secured Spring app responds to missing, invalid, or expired tokens using AuthenticationEntryPoint and AccessDeniedHandler. You practise Spring Security 6 & JWT Authentication with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Spring Security 6 & JWT Authentication?

No prior experience is required. Spring Security 6 & JWT Authentication on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Handling Authentication Errors and Entry Points” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Spring Security 6 & JWT Authentication lesson?

Yes. Every Spring Security 6 & JWT Authentication lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Designing the JWT Authentication Flow
  2. Implementing a Custom JWT Filter
  3. AuthenticationManager and Provider Integration
  4. Handling Authentication Errors and Entry Points
← Back to Spring Security 6 & JWT Authentication