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 表示用户有权限,只是访问是被禁止的(可以理解为,用户有权限,但是某些目录禁止访问)

以上为个人经验,希望能给大家一个参考,也希望大家多多支持www.887551.com。