spring security 中统一处理 authenticationexception 的核心是自定义 authenticationentrypoint,它在未认证请求被拒绝时(如无 token、token 过期)接管响应逻辑,返回 json 格式 401 错误而非重定向或 html 页面。

Spring Security 中 AuthenticationException 的统一响应处理,核心在于自定义 AuthenticationEntryPoint,它负责在未认证请求(如未带 token、token 过期、登录失败后重定向等)被拒绝时,决定如何响应客户端。
为什么需要自定义 AuthenticationEntryPoint
默认情况下,Spring Security 在未认证访问受保护资源时,会返回 302 重定向到登录页(基于表单登录)或抛出 401 Unauthorized(基于 JWT/无状态 API)。但 REST API 通常期望返回 JSON 格式的错误提示(如 {"code":401,"msg":"未登录"}),而非重定向或 HTML 页面。自定义 EntryPoint 就是为了接管这个“未认证入口”的响应逻辑。
实现自定义 AuthenticationEntryPoint
只需实现 AuthenticationEntryPoint 接口,并重写 commence() 方法:
- 方法参数包含
HttpServletRequest、HttpServletResponse和抛出的AuthenticationException(可能是InsufficientAuthenticationException、AccountExpiredException等子类) - 在此方法中可设置状态码(通常是 401)、响应头(如
Content-Type: application/json)和响应体 - 注意:此时请求尚未进入 Filter Chain 后续环节,不能依赖 SecurityContext 或 Principal
示例代码:
@Component
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException {
response.setStatus(HttpStatus.UNAUTHORIZED.value());
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(
"{\"code\":401,\"msg\":\"" +
(authException != null ? authException.getMessage() : "未认证") +
"\"}"
);
}
}
在 Security 配置中注册 EntryPoint
将自定义 EntryPoint 注入到 HttpSecurity 配置中,通常在 configure(HttpSecurity http) 或基于 SecurityFilterChain 的 Bean 中设置:
- 使用
http.exceptionHandling().authenticationEntryPoint(...) - 确保该配置适用于你的认证方式(JWT、OAuth2、Form Login 等)
- 若同时使用多种认证机制(如 JWT + Basic Auth),EntryPoint 会统一生效于所有未认证场景
基于 Java Config 示例:
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authz -> authz
.requestMatchers("/api/public/**").permitAll()
.requestMatchers("/api/private/**").authenticated()
)
.exceptionHandling(ex -> ex.authenticationEntryPoint(restAuthenticationEntryPoint))
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
return http.build();
}
区分不同异常类型(可选进阶)
虽然 commence() 只接收 AuthenticationException,但你可以通过 instanceof 判断具体异常类型,返回更精准的提示:
-
InsufficientAuthenticationException→ “缺少认证凭证” -
BadCredentialsException→ 一般出现在登录流程中,EntryPoint 通常不触发(由 AuthenticationFailureHandler 处理) -
AccountExpiredException/CredentialsExpiredException→ 可在自定义UserDetailsService或AuthenticationProvider中抛出,EntryPoint 能捕获并响应
注意:登录失败(如密码错误)走的是 AuthenticationFailureHandler,不是 EntryPoint;EntryPoint 主要响应「未认证访问受保护资源」这一场景。
不复杂但容易忽略:务必确认你的安全配置已启用对应异常处理器,且没有其他过滤器提前写入响应(如某些全局异常拦截器覆盖了 401 响应)。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











