Spring Security 的 Cors 授权预检错误

问题描述 投票:0回答:1

我很难获得一个在本地运行的 React 应用程序,该应用程序与也在本地运行的 Spring Boot 应用程序进行对话。我在 Spring Boot 应用程序中设置了以下 CorsConfiguration:

@Configuration
public class CORsConfiguration implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").
                allowCredentials(true).allowedOrigins("http://localhost:5173", "http://localhost:5173/login").
                //allowedOriginPatterns("*").
                allowedHeaders("Authorization",
                        "Cache-Control",
                        "Content-Type",
                        "Accept",
                        "X-Requested-With",
                        "Access-Control-Allow-Origin",
                        "Access-Control-Allow-Headers",
                        "Origin").exposedHeaders("Access-Control-Expose-Headers",
                        "Authorization",
                        "Cache-Control",
                        "Content-Type",
                        "Access-Control-Allow-Origin",
                        "Access-Control-Allow-Headers",
                        "Origin").allowedMethods("GET", "OPTIONS", "POST", "PUT", "DELETE", "PATCH");
    }
}

我尝试手动添加与反应应用程序上当前设置的各种路线相对应的允许来源列表。我还尝试了 allowedOriginsPatterns 上的“*”模式,希望它能作为一个包罗万象的功能。但仅通过这种配置,我就全面遇到了全面禁止的错误。为了能够让一切顺利进行,我还必须在我的配置中添加以下 bean:

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http.addFilterBefore(new CORSFilter(), BasicAuthenticationFilter.class);
    http.cors().and().csrf().disable();
    return http.build();
}

CORSFilter 类是我创建的自定义类,当前只是将一些调试信息输出到 stdout:所有请求标头的列表,因为我想验证我在 React 中设置的授权承载令牌是否正确传递。

使用 http.cors().and().csrf().disable() 就位后,我可以发布一些登录凭据并从 Spring Boot 获取授权令牌,但是当我随后发送请求时包含该令牌的“授权”标头,我收到以下错误:

:5173/:1 Access to XMLHttpRequest at 'http://localhost:8080/check' from origin 'http://localhost:5173' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.

有什么想法我在这里出错了吗?特别奇怪的是,我将 CorsRegistry 设置为从我正在使用的源接受,但它似乎根本没有做任何事情,我可以获得任何通信的唯一方法是禁用整个事情(显然并没有禁用所有功能,因为它仍然阻止飞行前)。

java spring spring-boot cors
1个回答
0
投票

问题最终出在我最初添加的调试过滤器中,该过滤器是为了吐出有关我收到的请求的各种信息。

当我第一次开始收到 Cors 相关错误时,我发现了各种相关帖子,这些帖子在响应对象上手动设置标头。我实施了这些建议,然后在更改内容以使用 CorsConfiguration 后立即忘记了所有这些。删除所有这些手动标头集就可以正常工作了。

© www.soinside.com 2019 - 2024. All rights reserved.