I'm trying to implement token based authentication with node.js. The token generation is working. When a user logs in the token is being saved in a browser cookie. My problem is that I can read the token from the cookie with node.js on the server because it is passed with every request but as far as I know it is a better practice to pass the token in the header as x-access-token and I don't know if this is possible with a simple page load.
For example when I log in, get and save the token but after that I should be redirected to a protected location (e. g. by window.open("/protected", "_self")) and I can't set the header of this request.
My javascript code for login:
var httpRequest = new XMLHttpRequest();
var params = 'username=' + username.value + '&password=' + password.value;
httpRequest.open('POST', '/login', true);
httpRequest.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
httpRequest.responseType = "json";
httpRequest.onreadystatechange = function() {
if(httpRequest.readyState == 4 && httpRequest.status == 200) {
if(httpRequest.response.success){
setCookie("loginToken", httpRequest.response.token, 1);
window.open("/protected/", "_self");
}
showToast();
}
}
httpRequest.send(params);
Node.js is reading the token from cookie with cookie-parser when /protected is opened:
var token = req.cookies.loginToken;
The whole thing is working but with cookie not token in header. Should I use the cookie method and if not, is there a way to pass to token in the header?