The issue I have is Cookie
is not added to the request header therefore I receive a 403 status. To explain further I am implementing a system link where when a user opens a page, a request token is is fetched and added to the META
of the html and also saved in the document.cookie
. When the user decides to login, the fetch request below fetchSignIn
should automatically add a cookie because I am setting credentials: "include"
but it doesn't. I have looked at other examples but I don't understand where my implementation is wrong.
Login implementation using OOP
class Login {
// Private methods...
fetchSignIn (obj, url) {
console.log("Cookie ", document.cookie);
fetch(url, {
method: "POST",
mode: "cors",
credentials: "include",
body: JSON.stringify(obj),
headers: {
"Content-Type": "application/json",
"Authorization": "",
"X-XSRF-TOKEN": getQSelector('meta[name="_csrf"]').content
}
})
.then((response) => response.text())
.then((data) => {
console.log(data);
})
.catch((error) => {
console.error('Error: ', error.message);
});
}
}
Fetch token on opening of the page
window.addEventListener("DOMContentLoaded", (e) => {
_loadCSRF(CSRFDOMLOAD);
})
const _loadCSRF = (path) => {
fetch(path) // GET Request
.then((response) => response.json())
.then((data) => {
console.log(data);
document.cookie = data.headerName + "=" + data.token;
getQSelector('meta[name="_csrf_header"]').setAttribute("content", data.headerName);
getQSelector('meta[name="_csrf"]').setAttribute("content", data.token);
})
.catch((err) => console.error("Failed csrf fetch ", err));
}