0. 概述
以前我們配置 SpringSecurity 的方式是繼承 WebSecurityConfigurerAdapter
,然后重寫(xiě)其中的幾個(gè)方法:
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//配置 Spring Security 中的過(guò)濾器鏈
@Override
void configure(HttpSecurity http) {}
//配置路徑放行規(guī)則
@Override
void configure(WebSecurity web) {}
//配置本地認(rèn)證管理器
@Override
void configure(AuthenticationManagerBuilder auth) {}
//配置全局認(rèn)證管理器
@Override
AuthenticationManager authenticationManagerBean() {}
}
目前這個(gè)類(lèi)已經(jīng)過(guò)期,雖然可以繼續(xù)使用,但是總覺(jué)得別扭。那么它的替代方案是什么?下面我來(lái)為大家一一介紹。
1. HttpSecurity
原寫(xiě)法:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/**")
.authorizeRequests(authorize - > authorize
.anyRequest().authenticated()
);
}
新寫(xiě)法:
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.antMatcher("/**")
.authorizeRequests(authorize - > authorize
.anyRequest().authenticated()
)
.build();
}
2. WebSecurity
原寫(xiě)法:
@Override
public void configure(WebSecurity web) {
web.ignoring().antMatchers("/ignore1", "/ignore2");
}
新寫(xiě)法:
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) - > web.ignoring().antMatchers("/ignore1", "/ignore2");
}
WebSecurity配置不常使用,如果需要忽略Url,推薦通過(guò)
HttpSecurity.authorizeHttpRequests
的permitAll
來(lái)實(shí)現(xiàn)。
3. AuthenticationManager
原寫(xiě)法:
@Autowired
private UserDetailsService userDetailsService;
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
//Local
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
}
//Global
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
新寫(xiě)法:
@Autowired
private UserDetailsService userDetailsService;
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
//Local
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests((authz) - > authz
.anyRequest().authenticated()
)
.httpBasic(withDefaults())
.authenticationManager(new CustomAuthenticationManager());
}
//Global
@Bean
public AuthenticationManager authenticationManager(HttpSecurity httpSecurity) throws Exception {
return httpSecurity.getSharedObject(AuthenticationManagerBuilder.class)
.userDetailsService(userDetailsService)
.passwordEncoder(bCryptPasswordEncoder())
.and()
.build();
}
4. 心得
技術(shù)是不斷迭代的,我們作為技術(shù)人員,不能墨守成規(guī),要學(xué)會(huì)擁抱變化。
-
spring
+關(guān)注
關(guān)注
0文章
338瀏覽量
14295 -
過(guò)濾器
+關(guān)注
關(guān)注
1文章
427瀏覽量
19520 -
Spring Security
+關(guān)注
關(guān)注
0文章
2瀏覽量
5448
發(fā)布評(píng)論請(qǐng)先 登錄
相關(guān)推薦
評(píng)論