spring boot cors无法与react应用程序一起使用

d4so4syb  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(483)

所以正如标题提到的,我有一个spring引导后端,它为react前端提供restapi。我已经得到了许多cors问题,并尝试了多种方法。我不是spring安全方面的Maven,但非常感谢您能帮助我解决这个问题。
我的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;
}
busg9geu

busg9geu1#

你的方法没有用注解 @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;
}

相关问题