【问题标题】:Spring Boot CORS not working with React appSpring Boot CORS 不适用于 React 应用程序
【发布时间】:2021-05-29 06:45:53
【问题描述】:

正如标题所述,我有一个 Spring Boot 后端,它为 React 前端提供 REST API。我遇到了许多 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;
}

【问题讨论】:

    标签: spring spring-boot rest web cors


    【解决方案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;
    }
    

    【讨论】:

      猜你喜欢
      • 2017-01-31
      • 2017-10-30
      • 2018-03-21
      • 1970-01-01
      • 2020-11-19
      • 2022-01-06
      • 2018-03-09
      • 1970-01-01
      • 2016-04-20
      相关资源
      最近更新 更多