I'm trying to secure my NestJS based API with Auth0.
It doesn't feel right what I'm doing at this moment π₯΄.
I tried to use the NestJS documentation and also the Developing Backend APIs with Nest.js from Auth0 but I don't know what I'm doing.
Did anyone of you solved this problem already?
Can you provide some good resources or advice?
Here is my strategy implementation:
import { passportJwtSecret } from 'jwks-rsa';
import { ExtractJwt, Strategy, VerifiedCallback } from 'passport-jwt';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      secretOrKeyProvider: passportJwtSecret({
        cache: true,
        rateLimit: true,
        jwksRequestsPerMinute: 5,
        jwksUri: '${DOMAIN}/.well-known/jwks.json'
      }),
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      audience: 'http://localhost:3000',
      issuer: '${DOMAIN}'
    });
  }
  async validate(payload: any, done: VerifiedCallback) {
    if (!payload) {
      done(new UnauthorizedException(), false);
    }
    return done(null, payload);
  }
}
In the controller I use an AuthGuard:
@UseGuards(AuthGuard('jwt'))
I also want to retrieve the authenticated user's metadata from Auth0. Did anyone figure out how to do that?
    
Top comments (2)
I have not used auth0 but you can check a small repo I created a while ago. I used passport.
github.com/stunti/challenge-m-back...
Here is the solution:
Use Auth0 to secure your NestJS application
Matthias π€ γ» Aug 20 γ» 7 min read