Invalid token when implementing Node/Express example in Hapi

Please include the following information in your post:

  • Which SDK this is regarding: Hapi / Hapi-auth-jwt / jwks-rsa
  • SDK Version: 20.2.1 / 10.2.0 / 2.0.5
  • Platform Version: e.g. Node 14.17.4
  • Code Snippets/Error Messages/Supporting Details/Screenshots:

I have a successfully working version of the Node.js/Express test application from the Auth0 → Quick Start → Node.js page of my Auth0 account

I am trying to get it working using on a Hapi.js using jwks-rsa per the instructions on node-jwks-rsa/examples/hapi-demo at master · auth0/node-jwks-rsa · GitHub but am not being helped by those instructions being out of date for current Hapi versions.

I started with the basic Hapi-jwt2 example project listed as documented here:
node-jwks-rsa/examples/hapi-demo at master · auth0/node-jwks-rsa · GitHub and that is working as expected.

Following the example on the Quick Start this is my amended (and redacted) code, which returns an Invalid Token when passed exactly the same Bearer Token that authenticates on the Express example, so this is not an issue with timing/expiration of the template.

I think my initial problem was that the example uses key rather than secret in the jwt.strategyas using key errors out rather than giving anInvalid Token`

The other difference in my implementation to the jwks-rsa example is that it uses a direct validateFunc definition, rather than using the deafult validate call that I have used.

const Hapi = require('@hapi/hapi')
const jwt = require('hapi-auth-jwt2')
const jwksRsa = require('jwks-rsa')

const validate = async (decoded) => {
  return { isValid: true }
}

const init = async () => {
  const server = new Hapi.server({ port: 8000 })
  await server.register(jwt)
  server.auth.strategy('jwt', 'jwt', {
    complete: true,
    headerKey: 'authorization',
    tokenType: 'Bearer',
    secret: jwksRsa.hapiJwt2Key({
      cache: true,
      rateLimit: true,
      jwksRequestsPerMinute: 5,
      jwksUri: 'https://[my.Auth0.details]/.well-known/jwks.json'
    }),
    // Your own logic to validate the user.
    validate,
    verifyOptions: {
      audience: 'https://[my.Auth0.details],
      issuer: 'https://[my.Auth0.details]/',
      algorithms: ['RS256']
    }
  })
  server.auth.default('jwt')
  server.route([
    {
      method: 'GET',
      path: '/',
      config: {
        auth: false
      },
      handler: () => ({ text: 'Token not required' })
    },
    {
      method: 'GET',
      path: '/restricted',
      config: {
        auth: 'jwt'
      },
      handler: (request, h) => {
        const response = h.response({ text: 'You used a token' })
        response.header('Authorization', request.headers.authorization)
        return response
      }
    }
  ])
  await server.start()
  return server
}