【问题标题】:CORS Origin Spring Boot Jhipster - pre-flight failsCORS Origin Spring Boot Jhipster - 飞行前失败
【发布时间】:2016-07-08 14:49:58
【问题描述】:

我正在使用 jhipster v2.27.2 我通过取消注释 application.yml 中的行来启用 cors

jhipster:
async:
    corePoolSize: 2
    maxPoolSize: 50
    queueCapacity: 10000

cors: #By default CORS are not enabled. Uncomment to enable.
    allowed-origins: "*"
    allowed-methods: GET, PUT, POST, DELETE, OPTIONS
    allowed-headers: "*"
    exposed-headers:
    allow-credentials: true
    max-age: 1800

在“WebConfigurer”中

@Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = props.getCors();
        if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) {
            source.registerCorsConfiguration("/api/**", config);
            source.registerCorsConfiguration("/v2/api-docs", config);
            source.registerCorsConfiguration("/oauth/**", config);
        }
        return new CorsFilter(source);
    }

但是当我请求访问令牌时,我仍然看到这个错误

http://localhost:8080/oauth/token?username=admin&password=admin&grant_type=password&scope=read。 对预检请求的响应未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin”标头 资源。因此不允许使用原点“http://localhost:9090” 使用权。响应的 HTTP 状态代码为 401。

【问题讨论】:

    标签: spring-boot cors yaml jhipster


    【解决方案1】:

    看起来在默认的SecurityConfiguration 中,它没有跳过对 OPTIONS 的安全检查。

    尝试将以下antMatcher 添加到SecurityConfiguration.java 中的protected void configure(HttpSecurity http) 方法

    .antMatchers(org.springframework.http.HttpMethod.OPTIONS, "/api/**").permitAll()
    

    【讨论】:

      【解决方案2】:

      如果您忘记在指定的 URL 上注册 cors,有时会出现此问题。在 WebConfigurer 中查找 corsFilter 并添加这些行

       log.debug("Registering CORS filter");
              source.registerCorsConfiguration("/api/**", config);
      

      【讨论】:

        【解决方案3】:

        SecurityConfiguration.java 中的另一个选项。而不是在configure(HttpSecurity) 覆盖中使用antMatcher,而是在configure(WebSecurity) 覆盖中添加它...

        public void configure(WebSecurity web) throws Exception {
            web.ignoring()
                .antMatchers(HttpMethod.OPTIONS, "/**")
        

        【讨论】:

          猜你喜欢
          • 2019-06-24
          • 2013-08-02
          • 2017-10-19
          • 2020-01-26
          • 2021-04-03
          • 2016-07-05
          • 2019-02-25
          • 2014-12-05
          相关资源
          最近更新 更多