处理未经认证的请求 AuthenticationEntryPoint
大约 1 分钟
处理未经认证的请求 AuthenticationEntryPoint
1、简介
AuthenticationEntryPoint
是 Spring Security 中的一个接口,用于处理未经认证的请求。当用户访问需要认证的资源,但没有提供有效的认证信息时,Spring Security 会调用相应的 AuthenticationEntryPoint
来响应此请求。
2、作用
AuthenticationEntryPoint
主要有以下两个作用:
- 拒绝访问:当用户没有进行认证时,
AuthenticationEntryPoint
会阻止用户访问该资源,并返回 HTTP 状态码 401(Unauthorized)或 403(Forbidden),或者根据需要返回自定义的 HTTP 响应。 - 自定义响应:它允许开发者对未经认证的请求返回自定义的响应格式,比如 JSON 错误消息或其他用户友好的信息,而不是仅仅返回默认的 HTTP 状态码。
3、源码
public interface AuthenticationEntryPoint {
void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException;
}
4、配置
首先,你可以通过配置类来设置自定义的 AuthenticationEntryPoint
,例如自定义返回 JSON 格式的错误信息。
http.exceptionHandling(exception ->
exception.authenticationEntryPoint(new MyAuthenticationEntryPoint())); //请求未认证的处理
5、自定义实现
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
//获取错误信息
String localizedMessage = authException.getLocalizedMessage();
//创建结果对象
HashMap result = new HashMap();
result.put("code", -1);
result.put("message", "需要登录:" + localizedMessage);
//转换成json字符串
String json = JSON.toJSONString(result);
//返回响应
response.setContentType("application/json;charset=UTF-8");
response.getWriter().println(json);
}
}