What's difference between crossorigin anonymous and use-credentials

Viewed 3535

from MDN

anonymous

A cross-origin request (i.e., with Origin: HTTP header) is performed. But no credential is sent (i.e., no cookie, no X.509 certificate, and no HTTP Basic authentication is sent). If the server does not give credentials to the origin site (by not setting the Access-Control-Allow-Origin: HTTP header), the image will be tainted and its usage restricted.

use-credentials

A cross-origin request (i.e., with Origin: HTTP header) performed with credential is sent (i.e., a cookie, a certificate, and HTTP Basic authentication is performed). If the server does not give credentials to the origin site (through Access-Control-Allow-Credentials: HTTP header), the image will be tainted and its usage restricted.

but, what's the usage difference between them.

2 Answers

anonymous and use-credentials are attribute values which translate into requesting a resource with same-origin and include respectively.

When requesting a resource without specifying the crossorigin attribute (i.e. omitted), then you will make a no-CORS fetch. This should be used for resources which aren't protected by CORS.

When requesting a resource using crossorigin="anonymous" (or crossorigin="" as this is the default value) then you are switching it to a CORS request. This means that a resource protected by CORS (example: fetch()) would be sent to the browser if the response headers include

Access-Control-Allow-Origin: *

Note we are using the * wildcard, but this could be a also be specific origin.

Access-Control-Allow-Origin: https://example.com

When requesting a resource using crossorigin="use-credentials" then you are making a request for a resource which is protected by CORS and may also include private data, for example your banking information (for example: fetch("https://bank.com/my-transaction-history/")). In such cases, the response header should include:

Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: https://example.com
Vary: Cookie, Origin

The server receiving the request will have access to cookies, the Authorization header, client certificates to be able to authenticate the user and also the ability to set a cookie on the browser making the request using the Set-Cookie

Read more: https://jakearchibald.com/2021/cors/

The difference is that credentials are sent for requests from that element. Servers can require credentials in order to approve the request.

Related