I am making an ajax request using $.ajax. The response has the Set-Cookie header set (I\'ve verified this in the Chrome dev tools). However, the browser does
@atomkirk's answer didn't quite apply to me because
fetch APIBut the answer helped me learn these points:
fetch API CORS requests needs {credentials:'include'} for both sending & receiving cookies
For CORS requests, use the "include" value to allow sending credentials to other domains:
fetch('https://example.com:1234/users', { credentials: 'include' })... To opt into accepting cookies from the server, you must use the credentials option.
{credentials:'include'} just sets xhr.withCredentials=true
Check fetch code
if (request.credentials === 'include') { xhr.withCredentials = true }
So plain Javascript/XHR.withCredentials is the important part.
If you're using jQuery, you can set withCredentials using $.ajaxSetup(...)
$.ajaxSetup({ crossDomain: true, xhrFields: { withCredentials: true } });
If you're using AngularJS, the $http service config arg accepts a withCredentials property:
$http({ withCredentials: true });
If you're using Angular (Angular IO), the common.http.HttpRequest service options arg accepts a withCredentials property:
this.http.post(this.heroesUrl, hero, { withCredentials: true });
As for the request, when xhr.withCredentials=true; the Cookie header is sent
Before I changed xhr.withCredentials=true
Cookie request header.After the change xhr.withCredentials=true
Cookie request header with the same value, so my server treated me as "authenticated"As for the response: the server may need certain Access-Control-* headers
For example, I configured my server to return these headers:
Until I made this server-side change to the response headers, Chrome logged errors in the console like
Failed to load
https://{saml-domain}/saml-authn: Redirect fromhttps://{saml-domain}/saml-redirecthas been blocked by CORS policy:
The value of the
'Access-Control-Allow-Credentials'header in the response is''which must be'true'when the request's credentials mode is'include'. Originhttps://{your-domain}is therefore not allowed access.
The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
After making this Access-* header change, Chrome did not log errors; the browser let me check the authenticated responses for all subsequent requests.