relay-tools / react-relay-network-layer

ReactRelayNetworkLayer with middlewares and query batching for Relay Classic.
MIT License
277 stars 47 forks source link

Token not refreshing after user logs out and login again with different user. #53

Closed softglance closed 7 years ago

softglance commented 7 years ago

Below is the code implemented. It works for a single user. when user login is switched the token is not getting refreshed for the new token received from server. .

On server side:

networkLayer = !isBrowser() ? new Relay.DefaultNetworkLayer(GRAPHQL_URL,  {
      headers: {
        Authorization: store.get('jwt_token') ,
      },
      credentials: 'same-origin', 
    }
  ) : null;

On client side:

environment.injectNetworkLayer(new Relay.DefaultNetworkLayer(CLIENT_GRAPHQL_URL, { 
      headers: {
        Authorization: store.get('jwt_token') ,
      },
      credentials: 'same-origin',
     }));

On logout:

store.clearAll();

I also tried using react-relay-network-layer but facing same issue.

nodkz commented 7 years ago

Did you use authMiddleware with react-relay-network-layer? This middleware will take a token from the store for every request.

authMiddleware({
    token: () => store.get('jwt'),
    tokenRefreshPromise: (req) => {
      console.log('[client.js] resolve token refresh', req);
      return fetch('/jwt/refresh')
        .then(res => res.json())
        .then(json => {
          const token = json.token;
          store.set('jwt', token);
          return token;
        })
        .catch(err => console.log('[client.js] ERROR can not refresh token', err));
    },
  }),
softglance commented 7 years ago

Thanks! It works, now the token is getting refreshed. After I login the old data from the relay store is loading. I tried using the this.props.relay.forceFectch() but still not getting the new data of logged in user.

nodkz commented 7 years ago

I such case you should create a new Relay Environment and replace old one in Relay.Renderer. (parent component just replace prop environment by the new instance)

https://facebook.github.io/relay/docs/api-reference-relay-renderer.html

softglance commented 7 years ago

The above comment was useful. Thanks!