spring-security 如何从WebSecurityConfigurerAdapter进行迁移?

64jmpszr  于 2022-11-11  发布在  Spring
关注(0)|答案(1)|浏览(275)

由于WebSecurityConfigurerAdapter@Deprecated,我如何才能正确地移动到org.springframework.security.web.SecurityFilterChain
我的意思是,下面的过时配置的等效配置是什么?

@Configuration
static class HttpSecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().authenticated();
        http.formLogin();
        http.httpBasic();
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER);
        http.csrf().disable();
    }
}
xqk2d5yq

xqk2d5yq1#

this blog中所述,移除extends并暴露SecurityFilterChain

@EnableWebSecurity
static class HttpSecurityConfiguration {
    @public
    public SecurityFilterChain filterChain(HttpSecurity http) {
        http.authorizeRequests().anyRequest().authenticated();
        http.formLogin();
        http.httpBasic();
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER);
        http.csrf().disable();
        return http.build();
    }
}

理想情况下,您还应该重写授权部分。

@EnableWebSecurity
static class HttpSecurityConfiguration {
    @public
    public SecurityFilterChain filterChain(HttpSecurity http) {
        http
            .authorizeHttpRequests( (auth) -> auth.anyRequest().authenticated())
            .formLogin(Customizer.withDefaults())
            .httpBasic(Customizer.withDefaults())
            .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .csrf().disable();
        return http.build();
    }
}

相关问题