JWT Strategy

Verifying the Bearer Token

src/auth/strategies/jwt.strategy.ts

import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { JwtPayload } from '../auth.service';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(config: ConfigService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: config.getOrThrow<string>('JWT_SECRET'),
    });
  }

  // called only if the signature and expiry are valid; return value becomes req.user
  validate(payload: JwtPayload) {
    return { id: payload.sub, email: payload.email, roles: payload.roles };
  }
}

Example

TOKEN=eyJhbGciOiJIUzI1NiIs...
curl -H "Authorization: Bearer $TOKEN" http://localhost:3000/users/me
curl -i http://localhost:3000/users/me

Example output

{"id":12,"email":"[email protected]","roles":["customer"]}

HTTP/1.1 401 Unauthorized
{"message":"Unauthorized","statusCode":401}