迁移到Sping 6.X如何最好地迁移cors和matchers的Spring SecurityConfiguration

6l7fqoea  于 2023-10-20  发布在  Spring
关注(0)|答案(2)|浏览(130)

我正在迁移到Spring Framework 6,我有以下Spring Framework 2代码:

@Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                // Per https://security.stackexchange.com/questions/166724/should-i-use-csrf-protection-on-rest-api-endpoints stateless
                // should be fine. CSRF is not required for API-only services
//                .csrf().disable() // this was in sprint 2.7
                .csrf((csrf) -> csrf.disable())
                .cors().configurationSource(corsConfigurationSource())
                .and()
                .authorizeHttpRequests()
//                .authorizeRequests()
                .antMatchers("**/").permitAll()
                .antMatchers("/api/**").authenticated()
                //.anyRequest().authenticated()
                .and()
                .addFilterBefore(new AwsCognitoJwtAuthFilter(awsCognitoIdTokenProcessor), UsernamePasswordAuthenticationFilter.class);
        return http.build();
    }

我知道如何移动'.csrf()',但我在移动.cors()和'. authorizeHttp Requests()'时遇到问题。有没有人知道如何迁移这些(或有一个例子)?我试图使用https://www.baeldung.com/spring-cors,但这是srping 5不是6,我已经尝试了其他研究,但大多数参考是Spring5或以下.

uurv41yg

uurv41yg1#

在Stackoverflow上有很多关于这个主题的文章:如何但我总是建议检查文档:你应该首先阅读这些资源:Migration GuideConfiguration Migrations
在这种情况下,filterChain将有下一个主体:

@Bean
  public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
        .csrf(AbstractHttpConfigurer::disable);
    http.cors(configuration -> configuration.configurationSource(corsConfigurationSource()));

    http.authorizeHttpRequests(request -> {
          request.requestMatchers("/pattern").permitAll();
          request.requestMatchers("/api/**").authenticated();
          request.anyRequest().authenticated();
        })
    http.addFilterBefore(new AwsCognitoJwtAuthFilter(awsCognitoIdTokenProcessor), 
        UsernamePasswordAuthenticationFilter.class);
    return http.build();
  }
aydmsdu9

aydmsdu92#

正如安德烈丽莎所指出的:

request.requestMatchers("/pattern").permitAll();
request.requestMatchers("/api/**").authenticated();
request.anyRequest().authenticated();

才是正确的做法。

相关问题