Obsługa błędów uwierzytelniania i punktów wejścia
Dostosuj sposób, w jaki aplikacja Spring zabezpieczona JWT reaguje na brakujące, nieprawidłowe lub wygasłe tokeny, korzystając z AuthenticationEntryPoint i AccessDeniedHandler.
Obsługa błędów uwierzytelniania i punktów wejścia to bezpłatna lekcja Spring Security 6 & JWT Authentication na CoddyKit. To lekcja 4 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Spring Security 6 & JWT Authentication, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Spring Security 6 & JWT Authentication zawiera 4 lekcji w sumie.
Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.
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.
Często zadawane pytania
Czy lekcja „Obsługa błędów uwierzytelniania i punktów wejścia” jest bezpłatna?
Tak — pełny tekst „Obsługa błędów uwierzytelniania i punktów wejścia” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Spring Security 6 & JWT Authentication, przejdź na CoddyKit PRO. Kurs Spring Security 6 & JWT Authentication zawiera 4 lekcji w sumie.
Co nauczysz się w „Obsługa błędów uwierzytelniania i punktów wejścia”?
Dostosuj sposób, w jaki aplikacja Spring zabezpieczona JWT reaguje na brakujące, nieprawidłowe lub wygasłe tokeny, korzystając z AuthenticationEntryPoint i AccessDeniedHandler. Ćwiczysz Spring Security 6 & JWT Authentication z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.
Czy potrzebuję doświadczenia, aby zacząć Spring Security 6 & JWT Authentication?
Nie wymagamy żadnego doświadczenia. Spring Security 6 & JWT Authentication w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 4 z 4.
Ile czasu zajmuje lekcja „Obsługa błędów uwierzytelniania i punktów wejścia”?
Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.
Czy mogę pisać i uruchamiać kod w tej lekcji Spring Security 6 & JWT Authentication?
Tak. Każda lekcja Spring Security 6 & JWT Authentication zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.
Wszystkie lekcje w tym kursie
- Projektowanie procesu uwierzytelniania JWT
- Implementacja niestandardowego filtra JWT
- Integracja AuthenticationManager i providerów
- Obsługa błędów uwierzytelniania i punktów wejścia