I need to be able to copy the jwt auth token of a React app (stored in local storage, sent via 'authorization' header) to the cookie storage of my browser, but I am not sure the best way to go about this. I am needing to do this to be able to perform an authenticated non-ajax call to download a data file.
The React front-end running on one server makes calls to an API running on another server.
I have modified the API server to accept the authentication via both header and cookies:
function fromHeaderOrCookie(req) {
if(req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
return req.headers.authorization.split(' ')[1];
} else if(req.cookies && req.cookies.srrsua) {
return req.cookies.srrsua;
}
return null;
}
const jwtOptions = {
jwtFromRequest: ExtractJwt.fromExtractors([fromHeaderOrCookie]),
secretOrKey: config.secret
};
And in requests to the server, I add a cookie to the XHR responses:
function tokenForUser(user) {
const timestamp = new Date().getTime();
return jwt.encode({sub: user.id, iat: timestamp}, config.secret);
}
res.cookie('jwtauth', tokenForUser(user), { expires: new Date(Date.now() + config.cookieMaxAge), httpOnly: false });
While the cookie is being sent back to the React server (I see it the headers), I don't see it actually be set in the browser?
Can anyone suggest what I should do to have the browser actually apply the cookie? Also, are there other recommended approaches to making the token available for non-xhr authenticated requests?