Authentifizierungsfehler und Entry Points behandeln
Passen Sie an, wie Ihre durch JWT abgesicherte Spring-Anwendung auf fehlende, ungültige oder abgelaufene Tokens reagiert – mit AuthenticationEntryPoint und AccessDeniedHandler.
Authentifizierungsfehler und Entry Points behandeln ist eine kostenlose Spring Security 6 & JWT Authentication-Lektion auf CoddyKit. Dies ist Lektion 4 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Spring Security 6 & JWT Authentication-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Spring Security 6 & JWT Authentication-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
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:
AuthenticationEntryPointhandles 401 (unauthenticated)AccessDeniedHandlerhandles 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.
Häufig gestellte Fragen
Ist die Lektion „Authentifizierungsfehler und Entry Points behandeln“ kostenlos?
Ja — der vollständige Text von „Authentifizierungsfehler und Entry Points behandeln“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Spring Security 6 & JWT Authentication-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Spring Security 6 & JWT Authentication-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „Authentifizierungsfehler und Entry Points behandeln“?
Passen Sie an, wie Ihre durch JWT abgesicherte Spring-Anwendung auf fehlende, ungültige oder abgelaufene Tokens reagiert – mit AuthenticationEntryPoint und AccessDeniedHandler. Du übst Spring Security 6 & JWT Authentication mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um Spring Security 6 & JWT Authentication zu starten?
Keine Vorkenntnisse erforderlich. Spring Security 6 & JWT Authentication auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 4 von 4.
Wie lange dauert die Lektion „Authentifizierungsfehler und Entry Points behandeln“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser Spring Security 6 & JWT Authentication-Lektion Code schreiben und ausführen?
Ja. Jede Spring Security 6 & JWT Authentication-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- Den JWT-Authentifizierungsablauf entwerfen
- Einen benutzerdefinierten JWT-Filter implementieren
- Integration von AuthenticationManager und Providern
- Authentifizierungsfehler und Entry Points behandeln