0

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?

Andre M
  • 6,649
  • 7
  • 52
  • 93
  • Are you trying to store a cookie on the client programmatically (rather than relying on the server to set it in a response)? http://stackoverflow.com/questions/4825683/how-do-i-create-and-read-a-value-from-cookie ? – pdenes Aug 22 '16 at 18:21
  • The server is injecting the cookie into the response, but it doesn't get set. It does work if they are running on the same port. For now I have just created a proxy, but I wonder if this is CORS related or something equivalent? – Andre M Aug 23 '16 at 23:14

0 Answers0