Applies to: ✔️ Front Door Standard ✔️ Front Door Premium
什么是 CORS?
CORS(跨域资源共享)是一项 HTTP 功能,使在一个域中运行的 Web 应用程序能够访问另一个域中的资源。 To reduce the possibility of cross-site scripting attacks, all modern web browsers implement a security restriction known as same-origin policy. 这可以防止网页调用其他域中的 API。 CORS 提供了一种安全方式,允许一个源(源域)调用另一个源中的 API。
工作原理
There are two types of CORS requests, simple requests and complex requests.
简单请求:
The browser sends the CORS request with another Origin HTTP request header. The value of this header is the origin that served the parent page, which is defined as the combination of protocol,domain, and port. When a page from https://www.contoso.com attempts to access a user's data in the fabrikam.com origin, the following request header would be sent to fabrikam.com:
Origin: https://www.contoso.com
服务器可能会使用以下任意响应进行响应:
An Access-Control-Allow-Origin header in its response indicating which origin site is allowed. For example:
Access-Control-Allow-Origin: https://www.contoso.com
如果服务器在检查源标头之后不允许跨源请求,则会显示 HTTP 错误代码(如 403)
An Access-Control-Allow-Origin header with a wildcard that allows all origins:
Access-Control-Allow-Origin: *
复杂请求:
A complex request is a CORS request where the browser is required to send a preflight request (that is, a preliminary probe) before sending the actual CORS request. 如果原始 CORS 请求可以继续并且是对同一 URL 的 OPTIONS
请求,则预检请求会向服务器请求权限。
Tip
有关 CORS 流和常见问题的详细信息,请查看 REST API 的 CORS 指南。
通配符或单个源场景
CORS on Azure Front Door works automatically with no extra configuration when the Access-Control-Allow-Origin header is set to wildcard (*) or a single origin. Azure Front Door 将缓存第一个响应,确保请求将使用相同的标头。
If requests were sent to the Azure Front Door before CORS being set on your origin, you need to purge content on your endpoint content to reload the content with the Access-Control-Allow-Origin header.
多个源场景
如果需要 CORS 允许一个特定的源列表,情况会稍微复杂一些。 The problem occurs when the CDN caches the Access-Control-Allow-Origin header for the first CORS origin. When a different CORS origin makes another request, the CDN serves the cached Access-Control-Allow-Origin header, which doesn't match. 有多种方法可纠正此问题。
Azure Front Door 规则集
On Azure Front Door, you can create a rule in the Azure Front Door Rules Set to check the Origin header on the request. If it's a valid origin, your rule sets the Access-Control-Allow-Origin header with the correct value. In this case, the Access-Control-Allow-Origin header from the file's origin server is ignored and the AFD's rules engine completely manages the allowed CORS origins.
Tip
You can add more actions to your rule to modify other response headers, such as Access-Control-Allow-Methods.
Next step
了解如何创建 Front Door。