nextjs-auth0: Don't get IdToken nor AccessToken

I’m able to login to Auth0. But whenever I switch on any of the tokens, I don’t get a valid session any more. I never get an IdToken nor an AccessToken into my session for using them with Apollo authenticating in Hasura:

    // Store the id_token in the session. Defaults to false.
    storeIdToken: true,
    // Store the access_token in the session. Defaults to false.
    storeAccessToken: true,
    "@apollo/react-hooks": "3.1.3",
    "@apollo/react-ssr": "3.1.3",
    "@auth0/nextjs-auth0": "^0.10.0",
    "apollo-cache-inmemory": "1.6.5",
    "apollo-client": "2.6.8",
    "apollo-link-context": "1.0.19",
    "apollo-link-http": "1.5.16",
    "dotenv": "^8.2.0",
    "graphql": "14.5.8",
    "graphql-tag": "2.10.1",
    "isomorphic-unfetch": "^3.0.0",
    "js-cookie": "2.2.1",
    "next": "9.1.7",
    "react": "16.12.0",
    "react-dom": "16.12.0"

Tried also the example from https://github.com/vgrafe/nextjs-auth0-hasura But never got it working with Authorization Header only with anonymous, which is not what I require.

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 2
  • Comments: 15 (2 by maintainers)

Most upvoted comments

@tobkle @shansmith01 maybe this can help you:

lib/auth0.js

import { initAuth0 } from '@auth0/nextjs-auth0'

export default initAuth0({
  domain: process.env.AUTH0_DOMAIN,
  clientId: process.env.AUTH0_CLIENT_ID,
  clientSecret: process.env.AUTH0_CLIENT_SECRET,
  scope: process.env.AUTH0_SCOPE,
  redirectUri: process.env.REDIRECT_URI,
  postLogoutRedirectUri: process.env.POST_LOGOUT_REDIRECT_URI,
  audience: 'myaudience',
  session: {
    cookieSecret: process.env.SESSION_COOKIE_SECRET,
    cookieLifetime: process.env.SESSION_COOKIE_LIFETIME,
    storeIdToken: false,
    storeRefreshToken: false,
    storeAccessToken: true,
  },
})

apolloClient.js

import { ApolloClient } from 'apollo-client'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { HttpLink } from 'apollo-link-http'
import { setContext } from 'apollo-link-context'
import { onError } from 'apollo-link-error'
import fetch from 'isomorphic-unfetch'

let accessToken = null

const requestAccessToken = async () => {
  if (!!accessToken) return

  const res = await fetch('/api/session')
  if (res.ok) {
    const json = await res.json()
    accessToken = json.accessToken
  } else {
    accessToken = 'public'
  }
}

// return the headers to the context so httpLink can read them
const authLink = setContext(async (req, { headers }) => {
  await requestAccessToken()
  if (!accessToken || accessToken === 'public') {
    return {
      headers,
    }
  } else {
    return {
      headers: {
        ...headers,
        Authorization: `Bearer ${accessToken}`,
      },
    }
  }
})

// remove cached token on 401 from the server
const resetTokenLink = onError(({ networkError }) => {
  if (networkError && networkError.name === 'ServerError' && networkError.statusCode === 401) {
    accessToken = null
  }
})

const httpLink = new HttpLink({
  uri: process.env.API_URL,
  credentials: 'include',
  fetch,
})

export default function createApolloClient(initialState, ctx) {
  // The `ctx` (NextPageContext) will only be present on the server.
  // use it to extract auth headers (ctx.req) or similar.
  accessToken = null
  return new ApolloClient({
    ssrMode: Boolean(ctx),
    link: authLink.concat(resetTokenLink).concat(httpLink),
    cache: new InMemoryCache().restore(initialState),
  })
}

api/session.js

import auth0 from '../../lib/auth0'

export default async function session(req, res) {
  try {
    const s = await auth0.getSession(req)

    if (s) res.send(s)
    res.status(500).end(s)
  } catch (error) {
    res.status(error.status || 500).end(error.message)
  }
}

Steps

Auth0
  • Generate Auth0 Regular Web App (Next.js)
  • Generate Auth0 API with audience (‘myaudience’)
  • Add rules to set tokens and sync with hasura backend; docs
Hasura
  • Add HASURA_GRAPHQL_JWT_SECRET; config-generator
  • Add HASURA_GRAPHQL_UNAUTHORIZED_ROLE (e.g. role ‘anonymous’)
  • Add HASURA_GRAPHQL_ADMIN_SECRET
Next.js App
  • Install Auth0 and enable storeAccessToken and add audience from Auth0-API (without audience no jwt token) (e.g. lib/auth0.js)
  • Install Apollo to Next.js
  • Add link-context with jwt (e.g. apolloClient.js)
  • Add api/session-route to get session for client and server (e.g. api/session.js)

Hope that’s it 😃

Hey @Afsoon. Any chance you can share your repo please? I am also working on a project with Hasura, Apollo and Auth0, with SSR. I am going nuts figuring out a good way to pass the idToken from the backend into the apolloClient headers

Thanks

Also the examples in the folders examples/api-call-example in combination with examples/sample-api aren’t working. As soon as I set storeIdToken: true, I don’t get a session any more. If I have it on false, I get a session, but without token. Do I need to setup a special configuration in the Auth0 Dashboard somewhere in order to get that working?