📜 ⬆️ ⬇️

Features withCredentials

Many people are familiar with such a XmlHttpRequest flag as withCredentials, they know what it is for, which headers you need to use with it in a pair, so that the browser can properly handle the server's responses. And I also seemed to know, but I didn’t know what I did — I was on the ball, and everything worked as it should. But once faced with unexpected behavior, what I want to tell.

As stated in the www.w3.org/TR/cors/#omit-credentials-flag specification, withCredentials allows us to use user-credentials , i.e. cookies, authentication data and client SSL certificates.

I make a request to get cookies:

$.ajax ({ type: 'POST', url: authUrl, dataType: 'json' }); 

The server returns the correct response with:
')
 Set-Cookie:MYCOOKIE=7B6E846F8972DF580001CDCBF49316E; Path=/; HttpOnly 

Next, I appeal to the same address with the resulting cookie:

 $.ajax ({ type: 'GET', url: authUrl, dataType: 'json', cache: false, xhrFields: { withCredentials: true } }); 

This is where the unexpected happens to me: even though I indicated “withCredentials: true”, the cookie received from the first request is not sent in the second request.

It turns out that the cookie from the first request is not saved by the browser, and there is nothing to send with the second request.
I assumed that the reason is in HttpOnly, but I couldn’t check with the cookie without this flag, because I tried to add “withCredentials: true” to the first request, and the miracle happens - the browser is saved and sent to the second request.

Thus, it turns out that the indication “withCredentials: true” is necessary not only for sending “user-credentials” in the request to the server, but also for using them from the responses from the server. It seems to be logical, but the use of the word “request” in all specifications and descriptions is confusing, I hope not only me)

Ps. As if I missed this specification , where it is directly stated that in the absence of this attribute “cookies are to be ignored in response”, I’m two for my search skills. But I hope now many will be able to avoid possible misunderstandings.

Source: https://habr.com/ru/post/263417/


All Articles