为Spring Security 6迁移Spring Security配置

des4xlb0  于 2023-04-12  发布在  Spring
关注(0)|答案(1)|浏览(331)

bounty将在5天后到期。回答此问题可获得+50声望奖励。Peter Penzov正在寻找来自信誉良好的来源的答案

我有这个Spring Security代码,我想为Spring Security 6配置:

public void configure(final HttpSecurity http) throws Exception {

    http.authorizeRequests()
        .antMatchers(permittedAntMatchers())
        .permitAll();

    http.authorizeRequests().antMatchers("/**").authenticated();

    .....

    http.exceptionHandling()....;
  }

我得到的Cannot resolve method 'antMatchers' in 'ExpressionInterceptUrlRegistry'错误.你知道我如何才能正确迁移这个项目?

g0czyy6m

g0czyy6m1#

在升级到Spring 6之前,您可以升级到Spring security 5.8.x版本,为Spring security 6做准备。有迁移文档可以帮助您更改。Preparing for 6.0
Spring Security 6已经删除了WebSecurityConfigurerAdapter类。所以你不能使用public void configure(HttpSecurity http) throws Exception {方法。相反,你需要创建SecurityFilterChain Bean
下面是您的代码所需的更改。

@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http.authorizeHttpRequests().requestMatchers(permittedAntMatchers()).permitAll();
    http.authorizeHttpRequests().requestMatchers(AntPathRequestMatcher.antMatcher("/**")).authenticated();
    
    http.exceptionHandling().....;
    return http.build();
}

RequestMatcher[] permittedAntMatchers() {
    List<RequestMatcher> matchers = new ArrayList<>();
    matchers.add(AntPathRequestMatcher.antMatcher(HttpMethod.POST, "/users/*")); // Sample
    // Add all your matchers
    return matchers.toArray(new RequestMatcher[0]);
}

相关问题