CORS: Cross-Origin Resource Sharing

CORS: Cross-Origin Resource Sharing

CORS, or Cross-Origin Resource Sharing, is a security feature implemented by browsers to prevent malicious websites from making unauthorized requests to a different domain than the one that served the web page. This article explains the basics of CORS and its headers.

1. Origin

Description:

  • The origin of a URL is composed of the protocol, domain, port, and path.
  • Example: https://example.com:8080/fooProtocol: httpDomain: example.comPort: 8080Path: /foo

Illustration: Shows the structure of a web URI and defines the origin.

2. Same-Origin Policy

Description:

  • The same-origin policy restricts how documents or scripts loaded from one origin can interact with resources from another origin.
  • Cross-origin requests are blocked by default for security reasons.

Illustration: Demonstrates a cross-origin request being blocked by the same-origin policy.

3. CORS Headers

Description:

  • CORS headers are set by the server to allow cross-domain interaction.
  • Example:Site: messenger.comRequest: Cross-origin request to FB.comHeaders: Access-Control-Allow-Origin: messenger.com

Illustration: Shows how CORS headers facilitate cross-origin requests.

4. Access-Control-Allow-Origin

Description:

  • This response header indicates which origins are permitted to access resources on the server.
  • Example: Access-Control-Allow-Origin: example.com

Illustration: Depicts a server allowing a request from example.com.

5. Access-Control-Allow-Credentials

Description:

  • When requests include credentials (e.g., cookies), this header ensures the server allows them.
  • Example:Request: Includes a cookieHeaders: Access-Control-Allow-Credentials: true

Illustration: Demonstrates a server handling a request with credentials.

6. Preflight Request

Description:

  • A preflight request is sent by the browser before the actual request to check if the CORS protocol is understood and allowed.
  • The preflight request uses the OPTIONS method.

Illustration: Explains the process and purpose of a preflight request.

Other CORS Headers:

  • Access-Control-Allow-Methods: Specifies the methods allowed by the server.
  • Access-Control-Allow-Headers: Lists the headers allowed by the server.
  • Access-Control-Max-Age: Indicates how long the results of a preflight request can be cached.


Understanding CORS and its headers is essential for securely handling cross-origin requests in web development.

要查看或添加评论,请登录

Piotr Klepuszewski的更多文章

社区洞察

其他会员也浏览了