为了返回给前端统一的数据格式,一般所有的数据都会以类似下面的方式返回:

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)));
    }
}

 

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐