Обработка ошибок аутентификации и точек входа
Настройте реакцию приложения Spring, защищённого JWT, на отсутствие, недействительность или истечение срока действия токенов с помощью AuthenticationEntryPoint и AccessDeniedHandler
«Обработка ошибок аутентификации и точек входа» — бесплатный урок Spring Security 6 & JWT Authentication на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Spring Security 6 & JWT Authentication, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Spring Security 6 & JWT Authentication содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
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.
Часто задаваемые вопросы
Урок «Обработка ошибок аутентификации и точек входа» бесплатный?
Да — полный текст урока «Обработка ошибок аутентификации и точек входа» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Spring Security 6 & JWT Authentication, подпишись на CoddyKit PRO. Курс Spring Security 6 & JWT Authentication содержит 4 уроков всего.
Чему я научусь в уроке «Обработка ошибок аутентификации и точек входа»?
Настройте реакцию приложения Spring, защищённого JWT, на отсутствие, недействительность или истечение срока действия токенов с помощью AuthenticationEntryPoint и AccessDeniedHandler Ты практикуешь Spring Security 6 & JWT Authentication с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Spring Security 6 & JWT Authentication?
Предыдущий опыт не требуется. Spring Security 6 & JWT Authentication на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «Обработка ошибок аутентификации и точек входа»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Spring Security 6 & JWT Authentication?
Да. Каждый урок Spring Security 6 & JWT Authentication включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Проектирование потока аутентификации JWT
- Реализация пользовательского фильтра JWT
- Интеграция AuthenticationManager и провайдеров
- Обработка ошибок аутентификации и точек входа