loading...

Using JWT-Authentication (Auth0) with NestJS 🔐

matthias profile image Matthias 🤖 ・1 min read

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?

Posted on by:

matthias profile

Matthias 🤖

@matthias

👨‍💻 Software Engineer 🚀 Working on all stacks 🏷️ #typescript #react #docker #kubernetes #devops #cloud #webdev

Discussion

markdown guide