Spring Security 从运行在不同地址上的React客户端向spring Boot oauth2资源服务器发出请求时出现CORS错误

u7up0aaq  于 2023-01-09  发布在  Spring
关注(0)|答案(1)|浏览(123)

这是一个oauth2资源服务器。当我通过postman请求传递oauth令牌时,我得到了正确的行为。我在react客户端中得到了错误:

Access to fetch at 'http://localhost:8080/folders' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

我的配置:

@Configuration
public class CorsConfig {

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

@Configuration
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests((authz) -> authz
                .anyRequest().authenticated()
            )
            .oauth2ResourceServer().jwt();
        return http.build();
    }

}

在Spring控制台日志中,我得到了o.s.s.w.a.i.过滤器安全拦截器:无法授权属性为[authenticated]的筛选器调用[OPTIONS/folders],但它成功完成了 Postman 请求。
我希望这个配置足够不给cors错误,相同的配置遵循许多stackoverflow答案/教程。任何帮助将不胜感激。

2j4z5cfb

2j4z5cfb1#

尝试使用资源服务器SecurityFilterChain@Bean配置CORS(而不是公开WebMvcConfigurer):

http.cors().configurationSource(corsConfigurationSource());

CorsConfigurationSource corsConfigurationSource() {
        final var configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:3000"));
        configuration.setAllowedMethods(Arrays.asList("*"));
        configuration.setAllowedHeaders(Arrays.asList("*"));
        configuration.setExposedHeaders(Arrays.asList("*"));

        final var source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);

        return source;
    }

此外,请确保加载此配置时带有断点或日志行。
示例取自my tutorials,您还可以在其中找到使用我的启动器的示例,这些示例允许仅从属性设置大多数安全配置(包括CORS)(大多数情况下不需要Java conf)。

相关问题