Search code examples
httpcorshttpresponsesame-origin-policyfetch-api

When should I really set "Access-Control-Allow-Credentials" to "true" in my response headers?


MDN says, when the credentials like cookies, authorisation header or TLS client certificates has to be exchanged between sites Access-Control-Allow-Crendentials has to be set to true.

Consider two sites A - https://example1.xyz.com and another one is B- https://example2.xyz.com. Now I have to make a http Get request from A to B. When I request B from A I am getting,

"No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://example1.xyz.com' is therefore not allowed access."

So, I'm adding the following response headers in B

response.setHeader("Access-Control-Allow-Origin", request.getHeader("origin"));

This resolves the same origin error and I'm able to request to B. When and why should I set

response.setHeader("Access-Control-Allow-Credentials", "true");

When I googled to resolve this same-origin error, most of them recommended using both headers. I'm not clear about using the second one Access-Control-Allow-Credentials.

  1. When should I use both?
  2. Why should I set Access-Control-Allow-Origin to origin obtained from request header rather than wildcard *?

Please quote me an example to understand it better.


Solution

  • Allow-Credentials would be needed if you want the request to also be able to send cookies. If you needed to authorize the incoming request, based off a session ID cookie would be a common reason.

    Setting a wildcard allows any site to make requests to your endpoint. Setting allow to origin is common if the request matches a whitelist you've defined. Some browsers will cache the allow response, and if you requested the same content from another domain as well, this could cause the request to be denied.