一文搞定 Spring Security 异常处理机制!

out.close();

另一类就是授权异常 AccessDeniedException,授权异常的实现类比较少,因为授权失败的可能原因比较少。

2.ExceptionTranslationFilter


ExceptionTranslationFilter 是 Spring Security 中专门负责处理异常的过滤器,默认情况下,这个过滤器已经被自动加载到过滤器链中。

有的小伙伴可能不清楚是怎么被加载的,我这里和大家稍微说一下。

当我们使用 Spring Security 的时候,如果需要自定义实现逻辑,都是继承自 WebSecurityConfigurerAdapter 进行扩展,WebSecurityConfigurerAdapter 中本身就进行了一部分的初始化操作,我们来看下它里边 HttpSecurity 的初始化过程:

protected final HttpSecurity getHttp() throws Exception {

if (http != null) {

return http;

}

AuthenticationEventPublisher eventPublisher = getAuthenticationEventPublisher();

localConfigureAuthenticationBldr.authenticationEventPublisher(eventPublisher);

AuthenticationManager authenticationManager = authenticationManager();

authenticationBuilder.parentAuthenticationManager(authenticationManager);

Map<Class<?>, Object> sharedObjects = createSharedObjects();

http = new HttpSecurity(objectPostProcessor, authenticationBuilder,

sharedObjects);

if (!disableDefaults) {

http

.csrf().and()

.addFilter(new WebAsyncManagerIntegrationFilter())

.exceptionHandling().and()

.headers().and()

.sessionManagement().and()

.securityContext().and()

.requestCache().and()

.anonymous().and()

.servletApi().and()

.apply(new DefaultLoginPageConfigurer<>()).and()

.logout();

ClassLoader classLoader = this.context.getClassLoader();

List defaultHttpConfigurers =

SpringFactoriesLoader.loadFactories(AbstractHttpConfigurer.class, classLoader);

for (AbstractHttpConfigurer configurer : defaultHttpConfigurers) {

http.apply(configurer);

}

}

configure(http);

return http;

}

可以看到,在 getHttp 方法的最后,调用了 configure(http);,我们在使用 Spring Security 时,自定义配置类继承自 WebSecurityConfigurerAdapter 并重写的 configure(HttpSecurity http) 方法就是在这里调用的,换句话说,当我们去配置 HttpSecurity 时,其实它已经完成了一波初始化了。

在默认的 HttpSecurity 初

  • 16
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值