Spring Boot CORS не работает с приложением React

#spring #spring-boot #rest #web #cors

#spring #spring-boot #остальное #веб #cors

Вопрос:

Итак, как указано в названии, у меня есть серверная часть spring boot, которая обслуживает REST API для интерфейса React. Я получал многочисленные проблемы с CORS и пробовал несколько методов. Я не эксперт по spring-security, но был бы очень признателен за помощь в решении этой проблемы.

Моя конфигурация CORS

 private static final String [] AUTH_WHITELIST = {
        // -- Swagger UI v2
        "/v2/api-docs",
        "/swagger-resources",
        "/swagger-resources/**",
        "/configuration/ui",
        "/configuration/security",
        "/swagger-ui.html",
        "/webjars/**",
        "/_ah/warmup",
        "/ae/test",
        // -- Swagger UI v3 (OpenAPI)
        "/v3/api-docs/**",
        "/swagger-ui/**",
        // other public endpoints of your API may be appended to this array
};

@Override
protected void configure(HttpSecurity http) throws Exception {

    http.csrf().disable().cors().configurationSource(corsConfigurationSource()).and().authorizeRequests()
            .antMatchers(HttpMethod.POST, "/login").permitAll()
            .antMatchers(AUTH_WHITELIST).permitAll()
            .anyRequest().authenticated();
    http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);


    http.apply(new JwtTokenFilterConfigurer(jwtTokenProvider,userDetailsService));

}

CorsConfigurationSource corsConfigurationSource() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    //config.setAllowedOriginPatterns(Arrays.asList("/*"));
    config.setAllowedOrigins(Arrays.asList("localhost:3000"));
    config.setAllowedHeaders(Arrays.asList("*"));
    config.setAllowedMethods(Arrays.asList("*"));
    config.setAllowCredentials(false);
    source.registerCorsConfiguration("/**", config);
    return source;
}
 

Ответ №1:

Ваш метод не снабжен @Bean аннотациями, поэтому я не думаю, что Spring автоматически создает или внедряет эту конфигурацию.

Попробуйте аннотировать метод с помощью @Bean :

 @Bean
public CorsConfigurationSource corsConfigurationSource() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowedOrigins(Collections.singletonList("localhost:3000"));
    config.setAllowedHeaders(Collections.singletonList("*"));
    config.setAllowedMethods(Collections.singletonList("*"));
    config.setAllowCredentials(Boolean.FALSE);
    source.registerCorsConfiguration("/**", config);
    return source;
}