欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

基于spring-security 401 403错误自定义处理方案

时间:2022-01-05 10:08:13|栏目:JAVA代码|点击:

spring-security 401 403错误自定义处理

为了返回给前端统一的数据格式,

一般所有的数据都会以类似下面的方式返回:

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

关于状态码401与403区别

401 表示用户没有权限(令牌,用户名,密码错误)

403 表示用户有权限,只是访问是被禁止的(可以理解为,用户有权限,但是某些目录禁止访问)

上一篇:浅谈java调用Restful API接口的方式

栏    目:JAVA代码

下一篇:JVM的类加载过程详细说明

本文标题:基于spring-security 401 403错误自定义处理方案

本文地址:http://www.codeinn.net/misctech/189246.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有