接上篇的容许跨域ajax
这里讲解Policy能够设置的选项:api
AddPolicy 在StartUp.ConfigureServices方法中调用;对于一些选项,先阅读一下,CORS是怎么工做的,可能会有帮助跨域
AllowAnyOrigin :容许CORS请求从任何源来访问,这是不安全的浏览器
注意:指定AllowAnyOrigin 和AllowCredentials 是一种不安全的配置,可能会致使 跨站请求伪造(cross-site request forgery:CSRF)。缓存
当应用使用这两个配置时,CORS服务返回一个无效的CORS响应。安全
SetIsOriginAllowedToAllowWildcardSubdomains:设置策略的 IsOriginAllowed 属性,使能够匹配一个配置的带通配符的域名服务器
options.AddPolicy("AllowSubdomain", builder => { builder.SetIsOriginAllowedToAllowWildcardSubdomains(); });
AllowAnyMethod:cookie
要容许一个CORS请求中指定的请求头,能够使用 WithHeaders 来指定。app
options.AddPolicy("AllowHeaders", builder => { builder.WithOrigins("http://example.com") .WithHeaders(HeaderNames.ContentType, "x-custom-header"); });
容许全部的请求头cors
options.AddPolicy("AllowAllHeaders", builder => { builder.WithOrigins("http://example.com") .AllowAnyHeader(); });
一个CORS中间件策略用 WithHeaders匹配特定的头,而请求中的头部(记录在Access-Control-Request-Headers)须要精确匹配WithHeader中的头部才能够跨域。
例如:
应用中策略
app.UseCors(policy => policy.WithHeaders(HeaderNames.CacheControl));
请求中的部分数据:
Access-Control-Request-Headers: Cache-Control, Content-Language
CORS中间件会拒绝这个请求,由于Content-Language(HeaderNames.ContentLanguage)没有在WithHeaders中列出来;
默认状况下,浏览器不会暴露全部的响应头给应用。
默承认用的响应头是:
Cache-Control
Content-Language
Content-Type
Expires
Last-Modified
Pragma
若是想让其余的头部对应用可用,能够调用 WithExposedHeaders:
options.AddPolicy("ExposeResponseHeaders", builder => { builder.WithOrigins("http://example.com") .WithExposedHeaders("x-custom-header"); });
默认状况下,浏览器不容许在跨域请求中发送证书。
证书中包含缓存(cookies)和HTTP验证协议(HTTP authentication schemes)。
要再跨域中发送证书,客户端(浏览器)必须设置 XMLHttpRequest.withCredentials 为 true。
直接使用 XMLHttpRequest
var xhr = new XMLHttpRequest(); xhr.open('get', 'https://www.example.com/api/test'); xhr.withCredentials = true;
使用JQuery
$.ajax({ type: 'get', url: 'https://www.example.com/api/test', xhrFields: { withCredentials: true } });
使用 Fetch API
fetch('https://www.example.com/api/test', { credentials: 'include' });
服务端也须要容许证书。使用AllowCredentials
options.AddPolicy("AllowCredentials", builder => { builder.WithOrigins("http://example.com") .AllowCredentials(); });
包含 Access-Control-Allow-Credentials 头部的HTTP 响应(HTTP Response) 将告诉浏览器:服务器容许跨域请求的证书;
若是浏览器发送证书,可是响应没有包含一个有效的 Access-Control-Allow-Credentials 头部 , 浏览器不会暴露响应给应用,跨域失败;
容许跨域证书是一个安全风险。
在跨域中,若是 Access-Control-Allow-Credentials 头部出现了,则意味着 设置为全部的源 (setting origin to " * ")会失效。
参考网址
https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.2#cors-policy-options