Set-Cookie on Browser with Ajax Request via CORS

后端 未结 2 1719
你的背包
你的背包 2020-11-29 04:56

Attempting to implement an ajax login / signup process (no refresh site with authentication). Using cookies for preserving state. I thought I\'d have this right by now but

相关标签:
2条回答
  • 2020-11-29 05:36

    Your AJAX request must be made with the "withCredentials" settings set to true (only available in XmlHttpRequest2 and fetch):

        var req = new XMLHttpRequest();
        req.open('GET', 'https://api.bobank.com/accounts', true); // force XMLHttpRequest2
        req.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
        req.setRequestHeader('Accept', 'application/json');
        req.withCredentials = true; // pass along cookies
        req.onload = function()  {
            // store token and redirect
            let json;
            try {
                json = JSON.parse(req.responseText);
            } catch (error) {
                return reject(error);
            }
            resolve(json);
        };
        req.onerror = reject;
    

    If you want a detailed explanation on CORS, API security, and cookies, the answer doesn't fit in a StackOverflow comment. Check out this article I wrote on the subject: http://www.redotheweb.com/2015/11/09/api-security.html

    0 讨论(0)
  • 2020-11-29 05:47

    I had a similiar problem, and it turned out that the browser settings were blocking third-party cookies (Chrome > Settings > Advanced Settings > Privacy > Content Settings > Block third-party cookies and site data). Unblocking solved the problem!

    0 讨论(0)
提交回复
热议问题