我想 Spring 安全升级到6.0,但WebSecurityConfigurerAdapter已弃用

iqih9akk  于 2023-08-05  发布在  Spring
关注(0)|答案(1)|浏览(367)

我想把springboot项目的安全性从5.7.3升级到6.0,但是WebSecurityConfigurerAdapter已经被弃用了。

@Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

字符串
WebSecurityConfigurerAdapter.authenticationManager()在6.0中已消失
我应该去哪里上同样的课?
我尝试注入AuthenticationManagerBuilder来构建一个AuthenticationManager;
但是它告诉我必须指定authenticationManager。

p8ekf7hl

p8ekf7hl1#

在最新版本的spring Boot 3.1.1**WebSecurityConfigureAdaptor,@EnableWebFluxSecurity,springSecurityFilterChain,.csrf(),ServerHttpSecurity & .pathMatchers()**被弃用,所以你必须修改代码。
如果你使用的是spring Boot 3,可以参考以下代码:

@EnableWebSecurity
@Configuration
@RequiredArgsConstructor
public class SecurityConfig {

    private final UserDetailServiceImpl userDetailsService;

    private final BCryptPasswordEncoder encoder;

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

       http.csrf(csrf -> csrf.disable())
            .authorizeRequests().
            requestMatchers("/category/add")
            .authenticated()
            .requestMatchers("/authenticate","/register").permitAll()
            .anyRequest()
            .authenticated()
            .and().exceptionHandling(ex -> ex.authenticationEntryPoint(point))
            .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
    http.addFilterBefore(filter, UsernamePasswordAuthenticationFilter.class);
    return http.build();

    }

    @Bean
    public AuthenticationManager authenticationManager() throws Exception {
        return new CustomAuthenticationManager();
    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        authenticationProvider.setUserDetailsService(userDetailsService);
        authenticationProvider.setPasswordEncoder(encoder);
        return authenticationProvider;
    }
}

字符串
CustomAuthenticationManager:

public class CustomAuthenticationManager implements AuthenticationManager {

    @Autowired
    private DaoAuthenticationProvider authenticationProvider;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        return authenticationProvider.authenticate(authentication);
    }
}

相关问题