【问题标题】:Issue with CORS and error and Access-Control-Allow-Origin headerCORS 和错误以及 Access-Control-Allow-Origin 标头的问题
【发布时间】:2021-01-01 03:51:33
【问题描述】:

您好,我无法在我的项目中禁用 CORS。我使用自定义过滤器和 Spring Security Config 进行 CORS 配置。我已经看到了这个出色的答案:Can you completely disable CORS support in Spring?

但是当我尝试了以下实现时,我仍然收到 CORS 错误:

CORS 配置:

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
class CorsFilter @Autowired
constructor() : CorsFilter(configSrc()) {
    companion object {

    private fun configSrc(): UrlBasedCorsConfigurationSource {
        val config = CorsConfiguration()
        config.allowCredentials = true
        config.addAllowedOrigin("http://127.0.0.1:3000")
        config.addAllowedHeader("*")
        config.addAllowedMethod("*")
        val src = UrlBasedCorsConfigurationSource()
        src.registerCorsConfiguration("/**", config)
        return src
    }
}

}

我也尝试将允许的来源设置为如下所示,但没有结果:

config.addAllowedOrigin("http://127.0.0.1:3000")

这些是来自正在进行的 OPTIONS 请求的响应标头:

这是我得到的确切错误:

您能否指出任何其他想法或为什么会发生这种情况?我认为这将是一个很容易解决的问题,但它最终花费了我很多时间。

谢谢

【问题讨论】:

  • 您确定Access-Control-Allow-Origin 标头出现在您从错误消息中用绿色掩盖的URL 获得的响应中吗? (是这个掩码 URL 的响应标头的图像吗?)
  • 我该如何检查?我是否需要访问前端,即请求的来源?
  • 是的。我假设第一张图片(带有响应标题)也来自您的浏览器。在浏览器开发人员工具的网络选项卡中,您应该找到这个特定的调用(在错误消息中被绿色掩盖的那个)并检查它是否包含此标头。错误消息似乎表明它没有。该端点是需要返回此响应标头的端点。
  • Access-Control-Allow-Origin 标头作为响应标头存在,值为“127.0.0.1:3000”。响应标头的图像就是这个被屏蔽的 URL
  • 您使用的是谷歌浏览器吗?如果是这样,那么这很可能是原因:stackoverflow.com/questions/10883211/…

标签: java spring spring-boot kotlin cors


【解决方案1】:

要提出替代方案,您可以在前端使用包 http-proxy-middleware (https://github.com/chimurai/http-proxy-middleware),您可以使用它来更改原始 URL 并代理 Origin 标头

【讨论】:

    【解决方案2】:

    添加以下类来解决 CORS 问题。

    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.CorsRegistry;
    import org.springframework.web.servlet.config.annotation.EnableWebMvc;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    @Configuration
    @EnableWebMvc
    public class WebConfig implements WebMvcConfigurer {
    
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").allowedOrigins("*").allowedHeaders("*").allowedMethods("*");
        }
    }
    

    【讨论】:

      【解决方案3】:

      我让它在这个配置下工作

      @Configuration
      public class CorsConfig {
         @Bean
         public WebMvcConfigurer corsConfigurer() {
             return new WebMvcConfigurer() {
                @Override
                public void addCorsMappings(CorsRegistry registry) {
                  registry.addMapping("/**")
                          .allowedOrigins("http://localhost:4200");
                }
             };
         }
      }
      

      【讨论】:

        【解决方案4】:

        您可以尝试这样在应用类中添加CORS映射:

        @Bean
        public WebMvcConfigurer corsConfigurer() {
            return new WebMvcConfigurer() {
                    @Override
                    public void addCorsMappings(CorsRegistry registry) {
                        registry.addMapping("/api/v1/**")
                        .allowedHeaders("*")
                        .allowedOrigins("*")
                        .allowedMethods("GET", "POST", "PUT", "DELETE")
                        .allowCredentials(true)
                        .maxAge(3600);
                    }
                };
            }
        

        https://spring.io/guides/gs/rest-service-cors/

        【讨论】:

          【解决方案5】:

          这对我有用。

          @Override
          protected void configure(HttpSecurity httpSecurity) throws Exception {
              // We don't need CSRF for this example
              httpSecurity.csrf().disable().cors().configurationSource(corsConfigurationSource())
              ....
          }
          
          
          
              @Bean
              CorsConfigurationSource corsConfigurationSource() {
                  CorsConfiguration configuration = new CorsConfiguration();
                  configuration.setAllowedOrigins(Arrays.asList("*"));
                  configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
                  configuration.setAllowCredentials(true);
                  // the below three lines will add the relevant CORS response headers
                  configuration.addAllowedOrigin("*");
                  configuration.addAllowedHeader("*");
                  configuration.addAllowedMethod("*");
                  UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
                  source.registerCorsConfiguration("/**", configuration);
                  return source;
              }
          

          【讨论】:

            【解决方案6】:

            假设您使用 SpringBoot 安全性:

            在您的配置类中添加以下内容(它扩展了 WebSecurityConfigurerAdapter 并具有 @EnableWebSecurity 注解),添加cors配置:

                @Override
                protected void configure(HttpSecurity http) throws Exception {
                    http.cors().and()
                        //other config
                }
            
            //TODO needs to be secured on domain you wants to allow 
            @Bean CorsConfigurationSource corsConfigurationSource() { 
            final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); 
            source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues()); 
            return source; 
            } 
            

            【讨论】:

              猜你喜欢
              • 2021-12-02
              • 2019-06-17
              • 2017-11-24
              • 2017-12-11
              • 2021-10-20
              • 2018-03-04
              • 2018-09-19
              • 2019-06-19
              • 2016-11-06
              相关资源
              最近更新 更多