为了返回给前端统一的数据格式,一般所有的数据都会以类似下面的方式返回:
public class APIResultDto<T> {
/**
* 状态码:-1代表成功,具体参考APIErrorCode类
*/
private int er;
/**
* 状态描述,可以自行设置或使用APIErrorCode类中默认描述
*/
private String erMessage;
/**
* 实际返回实体,isSuccess()返回true时该字段有效
*/
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)));
}
}