spring-security 401 403错误自定义处理
为了返回给前端统一的数据格式,
一般所有的数据都会以类似下面的方式返回:
public class APIResultDto<T> {
private int er;
private String erMessage;
private T items;
}
但是一些框架,比如本文要说的spring-security是不按照我们自定义规范处理的,幸运的是spring-security框架给了我们可以定制化的地方,只需继承
ResourceServerConfigurerAdapter
重写
public void configure(ResourceServerSecurityConfigurer resources) throws Exception
方法即可,在里面添加自定义的针对授权时返回的401以及403错误码,
具体如下:
@Autowired
private AccessDeniedHandler accessDeniedHandler;
@Autowired
private AuthenticationEntryPoint authenticationEntryPoint;
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.authenticationEntryPoint(authenticationEntryPoint);
resources.accessDeniedHandler(accessDeniedHandler);
}
里面涉及到的AccessDeniedHandler以及AuthenticationEntryPoint
如下所示:
@Component
public class CustomizedAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException, ServletException {
response.setContentType("application/json;charset=UTF-8");
//按照系统自定义结构返回授权失败
response.getWriter().write(JSON.toJSONString(APIResultDto.failed(APIErrorCode.AUTH_FAILED)));
}
}
@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
response.setContentType("application/json;charset=UTF-8");
//按照系统自定义结构返回授权失败
response.getWriter().write(JSON.toJSONString(APIResultDto.failed(APIErrorCode.AUTH_FAILED)));
}
}
关于状态码401与403区别
401 表示用户没有权限(令牌,用户名,密码错误)
403 表示用户有权限,只是访问是被禁止的(可以理解为,用户有权限,但是某些目录禁止访问)
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。