【问题标题】:Spring boot, security Cors configuration problem: Response to preflight request doesn't pass access control check: It does not have HTTP ok statusSpring boot,安全 Cors 配置问题:对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态
【发布时间】:2021-02-13 05:28:45
【问题描述】:

我在 Spring Boot 和 Spring Security 中编写了一个 API,该 API 由 React 前端访问,get 方法运行良好。但是当谈到我们有一个选项作为预检的帖子时,它会返回 401 http 状态。随着我的发展,现在我只希望 cors 不会阻止任何东西。 Insomnia 或邮递员不会出现此错误,我可以在没有此错误的情况下执行请求。发生此错误的主要端点是 /oauth/token,即 Spring Boot 获取 Bearer 令牌的默认端点,我通过 react 应用发送到那里的帖子给出了此错误:

Access to XMLHttpRequest at 'http://localhost:8080/oauth/token' from origin 
'http://localhost:3000' has been blocked by CORS policy: Response to preflight 
request doesn't pass access control check: It does not have HTTP ok status.

我的弹簧配置:

网络配置

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
        .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS",  "HEAD", "TRACE", "CONNECT");
    }
}
@EnableWebSecurity
@EnableAuthorizationServer
@EnableResourceServer
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .cors()
                .and()
                .csrf().disable();
    }
}

在进行了一些搜索后,我认为这是 cors 或我未获得的某些许可,但会考虑其他方法。

【问题讨论】:

    标签: java spring spring-boot spring-mvc spring-security


    【解决方案1】:

    AFAIK 为了正确配置 CORS,您还需要指定允许的来源、标头和其他内容(如果适用于您的用例)。 所以你的 CORS 映射会变成:

    @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") //or whichever methods you want to allow
                    .allowedOrigins("*") //or www.example.com if you want to be more specific
                    .allowedHeaders("Content_Type", "Authorization"); //i also put Authorization since i saw you probably want to do so
        }
    

    检查this picture,也许它会让你更好地理解它是如何工作的。

    【讨论】:

    • 好的,如果现在我想允许所有标题,我可以放 ("*") 吗?
    • @IgorFroehner,根据allowedHeaders() 方法的文档,是的 - " * " 可用于允许所有标题。此外,默认情况下,所有标题都是允许的。见docs.spring.io/spring-framework/docs/current/javadoc-api/org/…
    • @IgorFroehner,如果这解决了您的问题,我将不胜感激支持/接受它作为答案
    猜你喜欢
    • 2021-09-06
    • 2020-06-06
    • 1970-01-01
    • 2021-07-11
    • 2020-02-11
    • 2020-01-14
    • 2019-07-07
    • 2021-03-17
    • 2019-08-09
    相关资源
    最近更新 更多