Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Forwarding client token cookie to server requests #560

Closed
fabiulous opened this issue Nov 28, 2016 · 2 comments
Closed

Forwarding client token cookie to server requests #560

fabiulous opened this issue Nov 28, 2016 · 2 comments

Comments

@fabiulous
Copy link

Hello,

I'm working on an isomorphic reactjs app, using axios for client and server requests.
When authenticating a user I use express-jwt to set the client cookie. Making a browser request to my protected endpoint works perfectly, but my problem is when the request is done on the server side (required to create the initial redux store).

I'm not being able to forward the client cookie to other requests made in the server side. Is there any way to forward my client cookies?

@jonjaques
Copy link

jonjaques commented Nov 30, 2016

I use a cookie to persist the token for SSR purposes, but then for all my API requests I send an Authorization header. So getToken function for express-jwt looks like this:

let token = null;
if (req.headers.authorization) {
  let bearer = req.headers.authorization.split(' ')
  if (bearer[0] === 'Bearer') {
    token = bearer[1]
  }
}
else if (req.cookies && req.cookies.token) {
  token = req.cookies.token;
}
return token;

If a token cookie is present on the server, I populate it into redux state (which is wasteful I know because we are sending it via initial state and cookie, but whatevs).

And then I have a special redux middleware to set the Authorization header in axios, which is read from the store.

Some code just to give you the idea; Of course the hard part is wiring up all the plumbing for this 😉 .

// called on both server and client immediately following store creation
export function initializeStore(store, http) {
  let token = cookie.load('token', { path: '/' })
  if (__SERVER__ && token && token.length) {
    store.dispatch(setToken(token))
  }
}

Then this is an abstracted part of my middleware, but runs on every action

export function buildContext(store) {
  axios.defaults.headers['Authorization'] = getBearerToken(store.getState())
}

@fabiulous
Copy link
Author

Great! My solution was very similar to yours, I ended up also adding the token to the store and dispatching it on every action.

Thanks!

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants