Search code examples
auth0

Migrating from Auth0.js to Auth0-spa.js - Jwt malformed


I'm trying to migrate my app from auth0 to auth0-spa.js. I've been able to get it almost working, and the code is definitely simpler with this new lib so I'd like to keep using it but I also need a valid jwt token for the backend.

I use the following middleware on my node server (express-jwt)

export const jwtCheckMiddleware = jwt({
    secret: '....',
    getToken: function (req) {
       if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
           return req.headers.authorization.split(' ')[1];
       }
    },
    issuer: `https://${environment.auth.auth0Domain}/`,
    algorithm: 'RS256'
});

Previous I would pass the idToken from auth0 and it worked. Now I get a token via await auth0.getTokenSilently(), however passing that to the middleware gives me "jwt malformed".

How can I get a valid JWT token from auth0-spa.js? Also, how would I ensure that the token I'm passing to the middlware is never expired?


Solution

  • Ok so I was able to get auth-spa.js to give me a jwt token by registering a custom API with Auth0 and then passing the API identifier as the audience.

    More info here: https://auth0.com/docs/getting-started/set-up-api

    const auth0 = createAuth0Client({
      audience: environment.auth.audience,  <-----API identifier of custom API in Auth0
      client_id: environment.auth.clientId,
      domain: environment.auth.clientDomain
    });
    

    After adding the audience getTokenSilently() gives me a JWT token which I pass to node. Then I had to add the audience in my jwt middleware:

    export const jwtCheckMiddleware = jwt({
        secret: jwks.expressJwtSecret({
            cache: true,
            rateLimit: true,
            jwksRequestsPerMinute: 5,
            jwksUri: `https://${environment.auth.auth0Domain}/.well-known/jwks.json`
        }),
        audience: environment.auth.auth0ApiAudience,  <!--- API identifier
        issuer: `https://${environment.auth.auth0Domain}/`,
        algorithms: ['RS256']
    });