java 全球cors在spring security 3中不起作用,0.0

z5btuh9x  于 2023-04-28  发布在  Java
关注(0)|答案(1)|浏览(113)

当我使用postman在本地测试我的应用程序时,它非常令人困惑,我能够访问任何/公共路径API,我做错了什么,但我发现我的代码真的没有做任何事情来保护cors,我遵循这个官方公会:
https://docs.spring.io/spring-security/reference/servlet/integrations/cors.html#page-title

public static final String[] URL_WHITELIST = new String[]{
            "/static/**",
            "/api/public/**"
    };
    public static final String[] URL_ANONYMOUS = new String[]{
            "/api/auth/sign-in",
    };

    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()
            //...
                .securityMatcher("/api/**")
                .authorizeHttpRequests()
                .requestMatchers(URL_ANONYMOUS).anonymous()
                .requestMatchers(URL_WHITELIST).permitAll()
                .anyRequest().authenticated();
        return http.build();
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource(){
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList(https://example.com,https://admin.example.com));
        configuration.setAllowedMethods(Arrays.asList("GET","POST","OPTIONS"));
        configuration.setMaxAge(3600L);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
w8f9ii69

w8f9ii691#

使用这个:

@Bean
  public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
      @Override
      public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedMethods("*");
      }
    };
  }

也更新您的SecurityFilterChain。不要禁用Cors。:

@Bean
  public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    return http
        .csrf()
        .disable()
        .cors()
        .and()
        .authorizeRequests.......

相关问题