Auth0: Implementing idToken expiry

framework

#1

I wanted to implement a custom fetch for my Apollo httpLink to handle expired or soon to be expired idTokens. Unfortunately, whenever a request to graph.cool is made with an expired token, there’s nothing distinguishable in the payload I get back that I could use to determine if the request failed because of an expired token.

For the following query, using an expired idToken…

const userQuery = gql`
  query {
    user {
      id,
      name
    }
  }
`;

I get this as result…

{ data: { user: null } }

In this case, I wouldn’t be able to tell if the access token expired, or if the user didn’t get created before using the createUser() mutation.

Any one any ideas on this?


#2

I don’t know the Auth0/Graphcool integration, but here’s how it works in my app using graphql-yoga and Apollo.

You’ll want to handle this on the client side. When the idToken expires, the access token should be expired too. You’ll want to log the user out on the client app (e.g. clear wherever you have the tokens stored) and prompt them to log in again.

I have a custom renewToken Apollo link that runs as the first link.

  if (isAuthenticated()) return {} // checks for accesstoken and that it's not expired
  if (!getIdToken()) return {} // if there's no access token or it's expired, is there an idToken?
  return renewToken() // if there's an idToken, try to renew the accesstoken
export const renewToken = () =>
  new Promise((resolve, reject) => {
    console.log("renewing token!")
    authWebInstance.checkSession({}, (err, result) => {
      if (err) {
        console.log(err)
        if (err.error === `login_required`) logout() // this signs the user out of everything and will prompt for a login
        // TODO: handle {error: "login_required"} better
        return reject(new Error(`Renewal Token Error: ${err.message}`))
      }
      // eslint-disable-next-line no-use-before-define
      setSession(result)
      return resolve()
    })
  })

#3

@LawJolla Thanks for your reply. I indeed want to detect this on the client side, see my example above. Problem is I can’t distinguish if the accessToken was valid on a call (or if my query just didn’t return any results) as there’s not error on the response when the token is expired.

@nilan Would you be able to assist by any chance?