CORS:凭证模式是’包含’

是的,我知道你在想什么 – 还有另一个CORS问题,但这次我很难过。

所以要开始,实际的错误信息:

XMLHttpRequest无法加载http://localhost/Foo.API/token 。 当请求的凭据模式为“include”时,响应中“Access-Control-Allow-Origin”标头的值不能是通配符“* 。 因此不允许来源’ http:// localhost:5000 ‘访问。 XMLHttpRequest发起的请求的凭据模式由withCredentials属性控制。

我不确定凭证模式的含义是’包含’

所以当我在邮递员中执行请求时,我没有遇到这样的错误:

在此处输入图像描述

但是,当我通过我的angularjs网络应用程序访问相同的请求时,我被这个错误困扰了。 这是我的angualrjs请求/回复。 你会看到响应是OK 200 ,但我仍然收到CORS错误:

小提琴请求和响应:

下图演示了Web前端到API的请求和响应

提琴手

所以基于我在网上阅读的所有其他post, 看起来我做的是正确的,这就是为什么我无法理解错误。 最后,这是我在angualrjs(登录工厂)中使用的代码:

在此处输入图像描述

API中的CORS实现 – 参考目的:

方法1使用:

 public static class WebApiConfig { public static void Register(HttpConfiguration config) { EnableCrossSiteRequests(config); } private static void EnableCrossSiteRequests(HttpConfiguration config) { var cors = new EnableCorsAttribute("*", "*", "*") { SupportsCredentials = true }; config.EnableCors(cors); } } 

方法2使用:

 public void Configuration(IAppBuilder app) { HttpConfiguration config = new HttpConfiguration(); ConfigureOAuth(app); WebApiConfig.Register(config); app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); app.UseWebApi(config); } 

提前谢谢了!

问题源于您的Angular代码:

withCredentials设置为true时,它会尝试与请求一起发送凭据或cookie。 因为这意味着另一个来源可能尝试进行经过身份validation的请求,所以不允许使用通配符(“*”)作为“Access-Control-Allow-Origin”标头。

您必须明确地响应在“Access-Control-Allow-Origin”标头中发出请求的原点才能使其工作。

我建议明确地将您希望允许进行身份validation请求的来源列入白名单,因为只需响应来自请求的来源意味着如果用户恰好有一个有效的会话,任何给定的网站都可以对您的后端进行经过身份validation的调用。

我在前一段时间写的这篇文章中解释了这些内容。

因此,您可以将withCredentials设置为false或实现原始白名单,并在涉及凭据时响应具有有效来源的CORS请求

为Angular 5和Spring Security定制CORS(Cookie基础解决方案)

在Angular端需要为Cookie传输添加选项标记withCredentials: true

 constructor(public http: HttpClient) { } public get(url: string = ''): Observable { return this.http.get(url, { withCredentials: true }); } 

在Java服务器端,需要为配置CORS策略添加CorsConfigurationSource

 @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Bean CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); // This Origin header you can see that in Network tab configuration.setAllowedOrigins(Arrays.asList("http:/url_1", "http:/url_2")); configuration.setAllowedMethods(Arrays.asList("GET","POST")); configuration.setAllowedHeaders(Arrays.asList("content-type")); configuration.setAllowCredentials(true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; } @Override protected void configure(HttpSecurity http) throws Exception { http.cors().and()... } } 

默认情况下,方法configure(HttpSecurity http)将使用corsConfigurationSource作为http.cors()

如果它有帮助,我使用离心机与我的reactjs应用程序,并在检查下面的一些评论后,我查看了离心机.js库文件,在我的版本中,有以下代码片段:

 if ('withCredentials' in xhr) { xhr.withCredentials = true; } 

删除这三行后,应用程序正常工作,如预期的那样。

希望能帮助到你!