15
votes

So we're creating a React-Native app using Apollo and GraphQL. I'm using JWT based authentication(when user logs in both an activeToken and refreshToken is created), and want to implement a flow where the token gets refreshed automatically when the server notices it's been expired.

The Apollo Docs for Apollo-Link-Error provides a good starting point to catch the error from the ApolloClient:

onError(({ graphQLErrors, networkError, operation, forward }) => {
  if (graphQLErrors) {
    for (let err of graphQLErrors) {
      switch (err.extensions.code) {
        case 'UNAUTHENTICATED':
          // error code is set to UNAUTHENTICATED
          // when AuthenticationError thrown in resolver

          // modify the operation context with a new token
          const oldHeaders = operation.getContext().headers;
          operation.setContext({
            headers: {
              ...oldHeaders,
              authorization: getNewToken(),
            },
          });
          // retry the request, returning the new observable
          return forward(operation);
      }
    }
  }
})

However, I am really struggling to figure out how to implement getNewToken(). My GraphQL endpoint has the resolver to create new tokens, but I can't call it from Apollo-Link-Error right?

So how do you refresh the token if the Token is created in the GraphQL endpoint that your Apollo Client will connect to?

2
The onError link runs after a request. I don't think you can simply forward to try again. Ideally, you can determine if your current token is still valid in the frontend e.g. by looking at the exp claim in a JWT. Then you could use this excellent link: github.com/newsiberian/apollo-link-token-refreshHerku
You can call your GraphQL enpoint using window.fetch. This is a bit more work but should be no problem for a single query. Simply POST to the endpoint with a JSON object containing query and optionally variables and operation.Herku

2 Answers

18
votes

The example given in the the Apollo Error Link documentation is a good starting point but assumes that the getNewToken() operation is synchronous.

In your case, you have to hit your GraphQL endpoint to retrieve a new access token. This is an asynchronous operation and you have to use the fromPromise utility function from the apollo-link package to transform your Promise to an Observable.

import React from "react";
import { AppRegistry } from 'react-native';

import { onError } from "apollo-link-error";
import { fromPromise, ApolloLink } from "apollo-link";
import { ApolloClient } from "apollo-client";

let apolloClient;

const getNewToken = () => {
  return apolloClient.query({ query: GET_TOKEN_QUERY }).then((response) => {
    // extract your accessToken from your response data and return it
    const { accessToken } = response.data;
    return accessToken;
  });
};

const errorLink = onError(
  ({ graphQLErrors, networkError, operation, forward }) => {
    if (graphQLErrors) {
      for (let err of graphQLErrors) {
        switch (err.extensions.code) {
          case "UNAUTHENTICATED":
            return fromPromise(
              getNewToken().catch((error) => {
                // Handle token refresh errors e.g clear stored tokens, redirect to login
                return;
              })
            )
              .filter((value) => Boolean(value))
              .flatMap((accessToken) => {
                const oldHeaders = operation.getContext().headers;
                // modify the operation context with a new token
                operation.setContext({
                  headers: {
                    ...oldHeaders,
                    authorization: `Bearer ${accessToken}`,
                  },
                });

                // retry the request, returning the new observable
                return forward(operation);
              });
        }
      }
    }
  }
);

apolloClient = new ApolloClient({
  link: ApolloLink.from([errorLink, authLink, httpLink]),
});

const App = () => (
  <ApolloProvider client={apolloClient}>
    <MyRootComponent />
  </ApolloProvider>
);

AppRegistry.registerComponent('MyApplication', () => App);

You can stop at the above implementation which worked correctly until two or more requests failed concurrently. So, to handle concurrent requests failure on token expiration, have a look at this post.

0
votes

If you are using JWT, you should be able to detect when your JWT token is about to expire or if it is already expired.

Therefore, you do not need to make a request that will always fail with 401 unauthorized.

You can simplify the implementation this way:

const REFRESH_TOKEN_LEGROOM = 5 * 60

export function getTokenState(token?: string | null) {
    if (!token) {
        return { valid: false, needRefresh: true }
    }

    const decoded = decode(token)
    if (!decoded) {
        return { valid: false, needRefresh: true }
    } else if (decoded.exp && (timestamp() + REFRESH_TOKEN_LEGROOM) > decoded.exp) {
        return { valid: true, needRefresh: true }
    } else {
        return { valid: true, needRefresh: false }
    }
}


export let apolloClient : ApolloClient<NormalizedCacheObject>

const refreshAuthToken = async () => {
  return apolloClient.mutate({
    mutation: gql```
    query refreshAuthToken {
      refreshAuthToken {
        value
      }```,
  }).then((res) => {
    const newAccessToken = res.data?.refreshAuthToken?.value
    localStorage.setString('accessToken', newAccessToken);
    return newAccessToken
  })
}

const apolloHttpLink = createHttpLink({
  uri: Config.graphqlUrl
})

const apolloAuthLink = setContext(async (request, { headers }) => {
  // set token as refreshToken for refreshing token request
  if (request.operationName === 'refreshAuthToken') {
    let refreshToken = localStorage.getString("refreshToken")
    if (refreshToken) {
      return {
        headers: {
          ...headers,
          authorization: `Bearer ${refreshToken}`,
        }
      }
    } else {
      return { headers }
    }
  }

  let token = localStorage.getString("accessToken")
  const tokenState = getTokenState(token)

  if (token && tokenState.needRefresh) {
    const refreshPromise = refreshAuthToken()

    if (tokenState.valid === false) {
      token = await refreshPromise
    }
  }

  if (token) {
    return {
      headers: {
        ...headers,
        authorization: `Bearer ${token}`,
      }
    }
  } else {
    return { headers }
  }
})

apolloClient = new ApolloClient({
  link: apolloAuthLink.concat(apolloHttpLink),
  cache: new InMemoryCache()
})

The advantage of this implementation:

  • If the access token is about to expire (REFRESH_TOKEN_LEGROOM), it will request a refresh token without stopping the current query. Which should be invisible to your user
  • If the access token is already expired, it will refresh the token and wait for the response to update it. Much faster than waiting for the error back

The disadvantage:

  • If you make many requests at once, it may request several times a refresh. You can easily protect against it by waiting a global promise for example. But you will have to implement a proper race condition check if you want to guaranty only one refresh.