Features withCredentials

    Many people are familiar with the XmlHttpRequest flag like withCredentials, they know what it is for, what headers should be used with it, so that the browser normally processes server responses. And I, too, seemed to know, but I didn’t know what — I was googling, and everything worked as it should. But once I came across unexpected behavior, which I want to tell about.

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

    I am making a request to receive cookies:

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

    The server returns the correct response with:

    Set-Cookie:MYCOOKIE=7B6E846F8972DF580001CDCBF49316E; Path=/; HttpOnly
    

    Next, I go to the same address with the received cookie:

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

    This is where the unexpected happens to me: although I specified “withCredentials: true”, the one received from the first request of the cookie 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 before that I tried to add “withCredentials: true” to the first request, and a miracle happens - the cookie is saved by the browser and it is sent successfully in the second request.

    Thus, it turns out that the indication “withCredentials: true” is necessary not only for sending “user-credentials” in the requestto the server, but also to use them from 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. Somehow I missed this specification , which explicitly states that in the absence of this attribute “cookies are to be ignored in response”, a deuce to me for my search skills. But I hope that now many will be able to avoid a possible misunderstanding.

    Also popular now: