Spring Boot集成WebFlux时,如何使用AuthenticationEntryPoint.commence?
AuthenticationEntryPoint.commence 规范用法与响应编写指南
AuthenticationEntryPoint 是Spring Security中处理未认证请求的核心接口——当用户尝试访问受保护资源但未通过认证时(比如没登录、token过期/无效),commence方法就会被触发,你可以在这里完全自定义返回给客户端的响应格式或跳转逻辑。
核心实现步骤
1. 实现接口,重写commence方法
commence方法有三个核心参数:
HttpServletRequest:获取当前请求的所有信息(比如请求路径、参数)HttpServletResponse:用来构建并返回响应AuthenticationException:触发认证失败的具体异常(比如BadCredentialsException、InsufficientAuthenticationException)
示例1:返回JSON格式的未认证响应(适合前后端分离API)
import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.AuthenticationEntryPoint; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; public class CustomAuthEntryPoint implements AuthenticationEntryPoint { @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException { // 设置响应状态码:标准的401未授权 response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 指定响应为JSON格式,编码UTF-8 response.setContentType("application/json;charset=utf-8"); // 构建响应体内容 Map<String, Object> result = new HashMap<>(); result.put("code", 401); result.put("msg", "请先登录或提供有效的认证凭证"); // 生产环境建议隐藏具体异常信息,换成通用提示 result.put("detail", authException.getMessage()); // 把响应体写入输出流 PrintWriter writer = response.getWriter(); writer.write(new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(result)); writer.flush(); writer.close(); } }
示例2:重定向到登录页面(适合传统Web应用)
public class LoginRedirectEntryPoint implements AuthenticationEntryPoint { @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException { // 携带原请求地址,登录后可以跳回原页面 String redirectUrl = "/login?redirect=" + request.getRequestURI(); response.sendRedirect(redirectUrl); } }
2. 配置到Spring Security过滤器链
把自定义的AuthenticationEntryPoint配置到Security的全局规则里,让它生效:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.web.SecurityFilterChain; @Configuration public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth // 配置哪些路径需要认证 .anyRequest().authenticated() ) // 绑定自定义的认证入口处理器 .exceptionHandling(exceptions -> exceptions .authenticationEntryPoint(new CustomAuthEntryPoint()) ); return http.build(); } }
关键注意点
- 别和
AccessDeniedHandler搞混:AuthenticationEntryPoint管的是未认证,AccessDeniedHandler管的是已认证但权限不足,两者职责不同。 - 响应状态码:建议用标准的
401 Unauthorized,不要随便用200带错误码,遵循HTTP规范。 - 异常信息:生产环境不要把原始异常信息返回给前端,避免泄露系统细节,换成“认证失败,请重试”这类通用提示。
内容的提问来源于stack exchange,提问作者Jahan Zinedine
相关产品推荐
相关产品推荐

