背景
进行前后端分离开发,在登录认证过程中需要抛出token异常,但是异常被servlet捕获并打印在控制台,而前端返回 "full authentication is required to access this resource"(访问此资源需要完全认证)。
解决办法
在自定义的过滤器里打断点,查看该异常所在的过滤器是否在exceptiontranslationfilter这个过滤器的后面,如果不在,则使用
.addfilterafter(异常所在的过滤器, exceptiontranslationfilter.class)
问题解决~
一、理想情况
在登录认证处理过程中一般都会涉及到token的处理,比如token过期、错误等。在正常的处理流程中我们应该是在新建一个jwtfillter类来重写onceperrequestfilter的dofilterinternal方法。比如:
@override protected void dofilterinternal(httpservletrequest request, httpservletresponse response, filterchain filterchain) throws servletexception, ioexception { // 令牌验证 final string token = request.getheader("authorization"); final string jwt; if (stringutils.isempty(token)){ throw new badcredentialsexception("token无效"); } }
由于security默认屏蔽usernamenotfoundexception并将其转换成badcredentialsexception处理,为了安全考虑,建议使用badcredentialsexception来抛给security处理。
然后在securityconfig类中配置过滤器链,如:
@configuration public class securityconfiguration { @bean public passwordencoder passwordencoder() { return new bcryptpasswordencoder(); } @bean public jwtfillter jwtfillter() { return new jwtfillter(); } @bean public authenticationentrypoint myauthenticationentrypoint() { return new myauthenticationentrypoint(); } @bean public securityfilterchain filterchain(httpsecurity http) throws exception { // 自定义配置 http.authorizehttprequests((requests -> requests // .requestmatchers("/product/list").hasauthority("product_list") // .requestmatchers("/product/save").hasauthority("product_save") // .requestmatchers("/product/list").hasrole("user") // .requestmatchers("/product/save").hasrole("admin") .requestmatchers("/user/info").hasrole("admin") .anyrequest().authenticated()) ) .addfilterbefore(jwtfillter(), authenticationfilter.class) .exceptionhandling(exception ->{ exception.authenticationentrypoint(myauthenticationentrypoint()); }) .csrf(abstracthttpconfigurer::disable) .formlogin(abstracthttpconfigurer::disable); // 返回新的过滤器链 return http.build(); } }
由于我禁用了formlogin登录表单,与之相关的usernamepasswordauthenticationfilter等过滤器会从过滤器链中移除,所以一般都会设置为在 authenticationfilter之前( authenticationfilter是最后一道过滤器)
为了实现前后端分离,要根据发生的异常告诉前端如何处理,所以还需要自定义一个authenticationentrypoint认证异常处理器(授权异常处理器的逻辑相同)并将其加入过滤器链中,我的自定义认证异常处理类如下:
public class myauthenticationentrypoint implements authenticationentrypoint { @override public void commence(httpservletrequest request, httpservletresponse response, authenticationexception authexception) throws ioexception, servletexception { // 向前端响应数据 responseutil.print(response,result.error(authexception.getmessage())); } }
(此处responseutil和result为我自定义的工具类,与本次事件无关)
然后在这里进行异常处理逻辑,通过authexception获取异常信息,然后就能正常将json格式的响应信息发送给前端。
二、发生异常
但是当运行代码后,得到的响应结果却与预期不符
而后端控制台也打印了一堆错误栈信息
很明显,该badcredentialsexception异常本应该被security捕获,结果居然被servlet容器给捕获了。仔细检查代码后能确定除了securityconfig以外都没有问题,那大概率是过滤器顺序有问题。找了很多资料都没有相应的解决办法(可能是我找的还不够多[doge])。
三、异常原因
既然是过滤器顺序有问题,那就看一下过滤器链吧(可恶,想了好久才想起来这一点)
在jwtfillter(你自己的jwt过滤器)里设置断点,查看filterchain里的过滤器顺序,发现jwtfillter在中间的位置,而exceptiontranslationfilter和authorizationfilter在最后面,我还以为
.addfilterbefore(jwtfillter(), authenticationfilter.class)
这段代码是将我的过滤器放在authorizationfilter的前一个位置呢,结果跑那么前面去了。然后再来看一下exceptiontranslationfilter是如何处理认证异常的:
private void dofilter(httpservletrequest request, httpservletresponse response, filterchain chain) throws ioexception, servletexception { try { chain.dofilter(request, response);// 此处对后续的链路进行异常捕获 } catch (ioexception var7) { throw var7; } catch (exception var8) { throwable[] causechain = this.throwableanalyzer.determinecausechain(var8); runtimeexception securityexception = (authenticationexception)this.throwableanalyzer.getfirstthrowableoftype(authenticationexception.class, causechain); if (securityexception == null) { securityexception = (accessdeniedexception)this.throwableanalyzer.getfirstthrowableoftype(accessdeniedexception.class, causechain); } if (securityexception == null) { this.rethrow(var8); } if (response.iscommitted()) { throw new servletexception("unable to handle the spring security exception because the response is already committed.", var8); } this.handlespringsecurityexception(request, response, chain, (runtimeexception)securityexception); } }
可以看到,该过滤器是对后续的链路进行异常捕获,所以自定义的jwtfilter应当放在exceptiontranslationfilter的后面,即
.addfilterafter(jwtfillter(), exceptiontranslationfilter.class)
于是,该异常便能正确被security捕获并发送给自定义认证异常处理器进行处理。所以写过滤器的时候一定要注意检查链路顺序啊[吐血]
不过我跟着视频学习的时候,对方并没有设置这个也能在自定义异常处理器中获取异常信息,就很奇怪.....估计是security的版本不同导致的吧
到此这篇关于security6.4.2 自定义异常中统一响应遇到的问题的文章就介绍到这了,更多相关security6.4.2 自定义异常统一响应内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论