spring-security配置(版本5.7.0-M2)

一、WebSecurityConfigurerAdapter过期后,通过@Bean创建 SecurityFilterChain 、WebSecurityCustomizer、AuthenticationManager

  • SecurityFilterChain 配置以前的HttpSecurity
  • WebSecurityCustomizer 配置以前的WebSecurity
  • AuthenticationManager 配置认证管理器默认实现ProviderManager

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .antMatchers(HttpMethod.OPTIONS, "/**").anonymous()
            .antMatchers("/login", "/logout", "/wm/**", "/register/**", "/kaptcha/**", "/**/non/**").permitAll()
            .antMatchers("/**").authenticated()
            .and()
            .authenticationProvider(new xxxProvider(userDetailsService))
            .authenticationProvider(new xxxProvider(userDetailsService))
            .csrf().disable()
            .headers();
    return http.build();
}
 
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
    return (web) -> web.ignoring().antMatchers("/swagger-ui.html", "/webjars/**", "/swagger-resources/**", "/v2/api-docs", "/attach/**", "/tmp/attach/**");
}
 
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception {
    return configuration.getAuthenticationManager();
}

二、以前的多个AuthenticationProvider如何使用
在之前的版本中,可以在HttpSecurity配置中调用.authenticationProvider()方法设置provider。

现在在SecurityFilterChain设置authenticationProvider()是没用的,要问为什么,只能说技术在别人手里,别人想怎么写就怎么写。
看源码在SecurityFilterChain的配置过程中HttpSecurity.authenticationProvider()将我们写好的provider设置到了一个AuthenticationManagerBuilder实例中,可是看HttpSecurity.build()方法,我是没有找到那个地方将provider设置到AuthenticationManager实例中,所以在调用时报错: No AuthenticationProvider found

 

 

现在的添加Provider

 


再看在HttpSecurity.build()中有多种config,这里直接看InitializeAuthenticationProviderBeanManagerConfigurer

 
这个类中的config其实是从ApplicationContext中去取Provider

 并且多个AuthenticationProvider实例返回null

 



到这里已经很清楚了,以前通过new 方式创建的provider没有注入到springIOC容器,所以在build阶段没有找到相应的实例,导致报错No AuthenticationProvider found

解决办法就是直接通过@Bean,或者@Component注入provider,这种方式只能有一个providerBean

 

 


当然也可以在AuthenticationManager初始化时设置,可以有多个provider,configuration.getAuthenticationManager()方法会获得一个默认的ProviderManager实现

 

 

 



三、看到这个迷宫一样的代码,其实我们可以思考一下参考它的代码,定义一个filter,providerManager,sessionManager来完成是不是根简单清晰呢。

posted @   穿越到打工界  阅读(622)  评论(1编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示