以前我们配置 SpringSecurity 的方式是继承 WebSecurityConfigurerAdapter
,然后重写其中的几个方法:
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//配置 Spring Security 中的过滤器链
@Override
void configure(HttpSecurity http) {}
//配置路径放行规则
@Override
void configure(WebSecurity web) {}
//配置本地认证管理器
@Override
void configure(AuthenticationManagerBuilder auth) {}
//配置全局认证管理器
@Override
AuthenticationManager authenticationManagerBean() {}
}
目前这个类已经过期,虽然可以继续使用,但是总觉得别扭。那么它的替代方案是什么?下面我来为大家一一介绍。
原写法:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/**")
.authorizeRequests(authorize - > authorize
.anyRequest().authenticated()
);
}
新写法:
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.antMatcher("/**")
.authorizeRequests(authorize - > authorize
.anyRequest().authenticated()
)
.build();
}
原写法:
@Override
public void configure(WebSecurity web) {
web.ignoring().antMatchers("/ignore1", "/ignore2");
}
新写法:
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) - > web.ignoring().antMatchers("/ignore1", "/ignore2");
}
WebSecurity配置不常使用,如果需要忽略Url,推荐通过
HttpSecurity.authorizeHttpRequests
的permitAll
来实现。
原写法:
@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();
}
新写法:
@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();
}
技术是不断迭代的,我们作为技术人员,不能墨守成规,要学会拥抱变化。
全部0条评论
快来发表一下你的评论吧 !