Gestión de errores de autenticación y puntos de entrada
Personalice cómo responde su aplicación Spring protegida con JWT ante tokens ausentes, no válidos o expirados mediante AuthenticationEntryPoint y AccessDeniedHandler.
Gestión de errores de autenticación y puntos de entrada es una lección gratuita de Spring Security 6 & JWT Authentication en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Spring Security 6 & JWT Authentication, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Spring Security 6 & JWT Authentication incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
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.
Aprende Java con un tutor de IA — gratis
Escribe y ejecuta código real en tu navegador, obtén ayuda instantánea de un tutor de IA disponible 24/7 y continúa donde lo dejaste en la web o en la aplicación.
- Cursos
- 12
- Lecciones
- 48
Preguntas frecuentes
¿La lección «Gestión de errores de autenticación y puntos de entrada» es gratis?
Sí — el texto completo de «Gestión de errores de autenticación y puntos de entrada» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Spring Security 6 & JWT Authentication, actualiza a CoddyKit PRO. El curso de Spring Security 6 & JWT Authentication incluye 4 lecciones en total.
¿Qué aprenderé en «Gestión de errores de autenticación y puntos de entrada»?
Personalice cómo responde su aplicación Spring protegida con JWT ante tokens ausentes, no válidos o expirados mediante AuthenticationEntryPoint y AccessDeniedHandler. Practicas Spring Security 6 & JWT Authentication con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Spring Security 6 & JWT Authentication?
No se requiere experiencia previa. Spring Security 6 & JWT Authentication en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.
¿Cuánto tiempo toma la lección «Gestión de errores de autenticación y puntos de entrada»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Spring Security 6 & JWT Authentication?
Sí. Cada lección de Spring Security 6 & JWT Authentication incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Diseño del flujo de autenticación con JWT
- Implementación de un filtro JWT personalizado
- Integración de AuthenticationManager y Provider
- Gestión de errores de autenticación y puntos de entrada