DEV Community

Matthias πŸ€–
Matthias πŸ€–

Posted on

4 2

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?

Postmark Image

"Please fix this..."

Focus on creating stellar experiences without email headaches. Postmark's reliable API and detailed analytics make your transactional emails as polished as your product.

Start free

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 πŸ€– β€’