0Pricing
Spring Security 6 & JWT Authentication · 课时

处理身份验证错误与入口点

使用 AuthenticationEntryPoint 和 AccessDeniedHandler 自定义 JWT 保护的 Spring 应用如何响应缺失、无效或已过期的令牌

处理身份验证错误与入口点 是 CoddyKit 上的免费 Spring Security 6 & JWT Authentication 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 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:

  • 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.

常见问题解答

「处理身份验证错误与入口点」课时是免费的吗?

是的 — 「处理身份验证错误与入口点」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Spring Security 6 & JWT Authentication 课程的其余内容,请升级到 CoddyKit PRO。 Spring Security 6 & JWT Authentication 课程共包含 4 节课。

「处理身份验证错误与入口点」这节课中我会学到什么?

使用 AuthenticationEntryPoint 和 AccessDeniedHandler 自定义 JWT 保护的 Spring 应用如何响应缺失、无效或已过期的令牌 你通过在浏览器中直接运行的动手代码来练习 Spring Security 6 & JWT Authentication,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Spring Security 6 & JWT Authentication 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Spring Security 6 & JWT Authentication 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。

「处理身份验证错误与入口点」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Spring Security 6 & JWT Authentication 课中编写并运行代码吗?

能。每节 Spring Security 6 & JWT Authentication 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 设计 JWT 身份验证流程
  2. 实现自定义 JWT 过滤器
  3. AuthenticationManager 与身份验证提供程序集成
  4. 处理身份验证错误与入口点
← 返回 Spring Security 6 & JWT Authentication