Home >Web Front-end >JS Tutorial >How Does CORS Preflighting Verify Request Permissions?

How Does CORS Preflighting Verify Request Permissions?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-18 21:49:041021browse

How Does CORS Preflighting Verify Request Permissions?

Understanding CORS: Preflighting Requests

Cross-Origin Resource Sharing (CORS) involves enabling controlled access to resources from different origins. To accomplish this, browsers implement a "preflight" mechanism to verify if a request is allowed. Here's how to implement preflighting an HTTP request correctly:

Server Response with Access-Control-Allow-Origin Header

As mentioned, the server must add the "Access-Control-Allow-Origin" header with an appropriate value (e.g., "*" to allow all origins) to its response. This header grants permission for the request.

Preflighting with the OPTIONS Request

To preflight a request, the browser sends an additional request using the HTTP OPTIONS method before the actual request. This request includes the following headers:

  • Access-Control-Request-Method: Specifies the method used for the actual request (e.g., POST, GET).
  • Access-Control-Request-Headers: Lists the additional headers that will be used in the actual request (e.g., X-Custom-Header).

Server Response to Preflight Request

The server should acknowledge these preflight headers in its response. If the request is allowed, the response should include:

  • Access-Control-Allow-Origin: Same value as in the preflight request.
  • Access-Control-Allow-Methods: List of allowed methods.
  • Access-Control-Allow-Headers: List of allowed headers.

Crucially, the "Access-Control-Allow-Headers" header must not have a value of "*", but it should match the headers specified in the "Access-Control-Request-Headers" header.

Once the server sends this response to the preflight request, the browser will make the actual request.

Additional Resources

For further comprehensive information on CORS, refer to the HTML5 Rocks documentation at: http://www.html5rocks.com/en/tutorials/cors/

The above is the detailed content of How Does CORS Preflighting Verify Request Permissions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn