Cross-origin Resource Sharing (CORS) is a mechanism of browsers that enables browsers to access resources from different sources without the restriction of the same Origin policy.

Cross-domain request

When accessing resources in different domains, protocols, or ports, the browser makes a cross-domain request.

The following shows the visit different resources from http://www.a.com/page.html

// Different files, not across domains
http://www.a.com/other.html 
// Different directories, not across domains
http://www.a.com/path/other.html

// Different protocols, cross-domain
https://www.a.com/other.html 

// Different ports, cross-domain
http://www.a.com:8080/other.html

// Different domain names, cross-domain
http://www.b.com/other.html
// Different domain name (parent domain), cross domain
http://a.com/other.html
// Different domain name (subdomain), cross domain
http://sub.a.com/other.html
// Different domain name (IP), cross domain
http:/ / 119.254.98.162 / other. HTML
Copy the code

Preflight Request

Before making a cross-domain request, the browser uses the OPTIONS method to make a pre-check request to know whether the server allows the cross-domain request. The server confirms that the request is allowed before making a formal HTTP request.

In the return of the precheck request, the server can also inform the client whether it needs to carry credentials.

A simple request

Browsers divide cross-domain requests into simple requests and non-simple requests. Simple requests do not trigger precheck requests.

Meeting the post condition is considered a simple request:

  • Use one of the following request methods:
    • GET
    • HEAD
    • POST
  • The request header information does not exceed the following:
    • Accept
    • Accept-Language
    • Content-Language
    • Content-TypeLimited to the following three
      • text/plain

      • multipart/form-data

      • application/x-www-form-urlencoded

Simple requests add the Origin field to the request header, and the server uses this value to decide whether or not to approve the request.

If the request is the same, the server responds with several additional fields:

  • Access – Control – Allow – Origin (must)Specifies the domain that allows access to the resource, either when requestedOriginThe value of theta, or theta*Accept any domain name request; When the specified value is not*The Vary field in the response header must contain Origin;
  • Access – Control – Allow – Credentials (optional)When the browser credentials are set to true, whether to allow the browser to read the response. Return true(the only valid value, case sensitive) and none of the other values. When this field returns true,Access-Control-Allow-OriginMust be the requestOriginThe value of, cannot be*; This field specifies whether the actual request can use the credentials when prechecking the response to the request; Simple requests are not prechecked. When the browser’s credentials are set to true, the browser cannot read the response if the response does not contain this field.
  • Access – Control – Expose – Headers (optional) :Whitelist, which lists the headers the server allows the browser to access By default,XMLHttpRequest.getResponseHeader()The method can only get the six simple response headers. If you want to get the other fields, you need to get them in theAccess-Control-Expose-HeadersSpecified. The six simple responses start with:
    • Cache-Control
    • Content-Language
    • Content-Type
    • Expires
    • Last-Modified
    • Pragma

Non-simple request

Non-simple requests are those that have special requirements on the server

For example, the request method is PUT or DELETE; For example, it contains request headers that are not qualified, such as Authorization or X-custom-header. For example, the content-type field is application/json;

For non-simple requests, the browser makes a pre-check request and receives a positive response before making a formal request.

Preview the request

The precheck request uses the OPTIONS method and includes the following fields:

  • Origin: indicates the source of the actual request.
  • Access-control-request-method: indicates the HTTP Method used in the actual Request.
  • Access-control-request-headers: specifies the additional header field carried by the actual Request.

Note: The pre-check request is automatically issued by the browser and these fields do not need to be manually set.

Precheck the response to the request

After receiving the pre-check Request, the server checks Origin, Access-Control-request-method, and access-Control-request-headers to confirm whether cross-source requests are allowed and then responds.

The response includes the following fields:

  • Access-control-allow-origin specifies the domain that allows Access to the resource. It has the same meaning as a simple request
  • Access-control-allow-methods specifies all HTTP Methods allowed in the actual request
  • Access-control-allow-headers specifies all header fields that are allowed in the actual request
  • Access-control-allow-credentials Specifies whether the Credentials can be used in actual requests. The meaning is the same as that of simple requests
  • Access-control-max-age specifies how long, in seconds, the results of precheck requests can be cached

Normal cross-domain request

After passing the precheck, the browser will add the Origin field in the request header for normal cross-domain requests just like simple requests.

The server’s response, like a simple request, must contain the Access-Control-Allow-Origin field.

PHP cross-domain middleware

Cross-domain resource sharing (CORS) middleware that supports the PHP-PSR specification.

Install dependencies

composer require reezy/cors 
Copy the code

configuration


      

return [
    // Whether to allow all fields
    'allowed-all-origins'   => env('APP_ENV')! = ='prod'.// The domain that allows access to the resource
    'allowed-origins'= > ['http://localhost'].// All header fields allowed in the actual request
    'allowed-headers'= > ['authorization'.'content-type'.'x-requested-with'].// All HTTP methods allowed in the actual request
    'allowed-methods'= > ['GET'.'POST'.'PUT'.'PATCH'.'DELETE'.'OPTIONS'].// ex: GET, POST, PUT, PATCH, DELETE
    // Whether the actual request can use the credentials
    'allowed-credentials'= >true.// Whitelist lists the headers that the server allows the browser to access
    // Six simple headers do not need to be specified: cache-Control, Content-language, Content-Type, Expires, Last-Modified, Pragma
    'exposed-headers'= > [].// How long can the results of precheck requests be cached, in seconds
    'max-age'= >10 * 86400,];Copy the code

reference

HTTP Access Control (CORS) developer.mozilla.org/zh-CN/docs/… The same Origin policy for browsers developer.mozilla.org/zh-CN/docs/…