I'm having trouble setting up Auth0 authentication using the passport-jwt library in a NestJS project. I've tried following the documentation, but I can't seem to get it to work. I'm not sure where I'm going wrong and would appreciate any guidance or suggestions on what to check or modify in my code.
What could be the reason for getting a 401 Unauthorized error when sending a GET request, with a valid bearer access token?
The request is even not call validate(payload: unknown): unknown
in jwt.strategy.ts
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { passportJwtSecret } from 'jwks-rsa';
/**
* @see https://auth0.com/blog/developing-a-secure-api-with-nestjs-adding-authorization/
*/
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
secretOrKeyProvider: passportJwtSecret({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: `${process.env.AUTH0_JWKS}`,
}),
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
audience: process.env.AUTH0_AUDIENCE,
issuer: `${process.env.AUTH0_ISSUER_URL}`,
algorithms: ['RS256'],
});
}
validate(payload: unknown): unknown {
console.log('Validating JWT payload:', payload);
return payload;
}
}
AUTH0_AUDIENCE is AUTH0_AUDIENCE
import { Module } from '@nestjs/common';
import { PassportModule } from '@nestjs/passport';
import { JwtStrategy } from './jwt.strategy';
import { HttpModule } from '@nestjs/axios';
import { ManagementService } from './management.service';
@Module({
imports: [PassportModule.register({ defaultStrategy: 'jwt' }), HttpModule],
controllers: [],
providers: [JwtStrategy, ManagementService],
exports: [PassportModule, ManagementService],
})
export class AuthModule {}
Usually if you are getting a 401 without any explanation it means you are either not sending a JWT as a Bearer <token>
format in the Authorization
header, or the JWT you are passing is invalid, most likely from expiration. To log more details in Nest, create a guard that extends AuthGuard('jwt')
and add this method to it
handleRequest(...args: Parameters<InstanceType<ReturnType<typeof AuthGuard>>['handleRequest']>) {
console.log(args);
return super.handleRequest(...args);
}
This will have Nest print out an object with keys like error
, info
, status
, context
, and more. You can use this to help debug what's going on.