存在CORS问题和错误以及Access-Control-Allow-Origin头部。

huangapple go评论75阅读模式
英文:

Issue with CORS and error and Access-Control-Allow-Origin header

问题

以下是您要翻译的内容:

你好,我无法在我的项目中禁用CORS。我使用了自定义过滤器和Spring Security配置来进行CORS配置。我看到了这个很棒的答案:https://stackoverflow.com/questions/44697883/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请求的响应头:

存在CORS问题和错误以及Access-Control-Allow-Origin头部。

这是我收到的确切错误:

存在CORS问题和错误以及Access-Control-Allow-Origin头部。

您能否指出任何额外的想法或者可能发生这种情况的原因?我原以为这将是一个简单的问题,但事实证明这花费了我相当多的时间。

谢谢

英文:

Hi I cant disable CORS in my project. I use a custom filter and Spring Security Config for the CORS configuration. I have seen this excellent answer: https://stackoverflow.com/questions/44697883/can-you-completely-disable-cors-support-in-spring

but when I have tried the below implementation I still get the CORS error:

CORS configuration:

@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
    }
}

}

Ive also tried setting the allowed origin to be like below with no results:

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

These are the Response headers from the proceeding OPTIONS request:

存在CORS问题和错误以及Access-Control-Allow-Origin头部。

This is the exact error I am getting:
存在CORS问题和错误以及Access-Control-Allow-Origin头部。

Could you please point out any additional ideas or why this might be happening? I thought that this would be a simple to fix issue but it has ended up consuming quite a lot of my time.

Thank you

答案1

得分: 2

你可以尝试在应用程序类中以以下方式添加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/

英文:

You can try adding CORS mapping in the application class in this way:

@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/

答案2

得分: 2

我已经使用这个配置使其工作正常:

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

I had it working with this configuration

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

答案3

得分: 1

假设您正在使用SpringBoot安全性:

在您的配置类中添加以下内容(该类扩展自WebSecurityConfigurerAdapter,并带有@EnableWebSecurity注解),添加CORS配置:

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and()
            //其他配置
    }
//TODO 需要在允许的域上进行安全设置
@Bean
CorsConfigurationSource corsConfigurationSource() {
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
    return source;
}
英文:

Assuming you work with SpringBoot security:

Add the following in your configuration class (which extends WebSecurityConfigurerAdapter and has @EnableWebSecurity
annotation), add cors configuration:

    @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; 
} 

答案4

得分: 1

这对我有效。

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    // 我们在这个示例中不需要 CSRF
    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);
    // 下面的三行代码将添加相关的 CORS 响应头
    configuration.addAllowedOrigin("*");
    configuration.addAllowedHeader("*");
    configuration.addAllowedMethod("*");
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}
英文:

This worked for me.

@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;
	}

答案5

得分: 1

将以下类添加以解决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("*");
    }
}
英文:

Add the below class to resolve the CORS issue.

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("*");
    }
}

答案6

得分: 1

为了提供一个替代方案,你可以在前端使用类似于 http-proxy-middleware 包(https://github.com/chimurai/http-proxy-middleware),通过它可以更改你的原始 URL 并代理 Origin 标头。

英文:

To suggest an alternative, you could use something such as the package http-proxy-middleware (https://github.com/chimurai/http-proxy-middleware) on your front end, you can use this to change your origin URL and proxy the Origin header

huangapple
  • 本文由 发表于 2020年9月14日 20:10:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/63884056.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定