DEV Community

Matthias 🤖
Matthias 🤖

Posted on

Using JWT-Authentication (Auth0) with NestJS 🔐

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);
  }
}

Enter fullscreen mode Exit fullscreen mode

In the controller I use an AuthGuard:

@UseGuards(AuthGuard('jwt'))
Enter fullscreen mode Exit fullscreen mode

I also want to retrieve the authenticated user's metadata from Auth0. Did anyone figure out how to do that?

Top comments (2)

Collapse
 
stunti profile image
Olivier Bregeras

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...

Collapse
 
matthias profile image
Matthias 🤖