typescript 36 lines · 7 steps

How a JWT strategy authenticates in NestJS

A Passport JWT strategy that verifies bearer tokens and re-checks the user on every request.

Explained by highlit
1import { Injectable, UnauthorizedException } from '@nestjs/common';
2import { PassportStrategy } from '@nestjs/passport';
3import { ExtractJwt, Strategy } from 'passport-jwt';
4import { ConfigService } from '@nestjs/config';
5import { UsersService } from '../users/users.service';
6 
7interface JwtPayload {
8 sub: string;
9 email: string;
10 role: string;
11}
12 
13@Injectable()
14export class JwtStrategy extends PassportStrategy(Strategy) {
15 constructor(
16 private readonly config: ConfigService,
17 private readonly usersService: UsersService,
18 ) {
19 super({
20 jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
21 ignoreExpiration: false,
22 secretOrKey: config.getOrThrow<string>('JWT_SECRET'),
23 issuer: config.get<string>('JWT_ISSUER'),
24 });
25 }
26 
27 async validate(payload: JwtPayload) {
28 const user = await this.usersService.findById(payload.sub);
29 
30 if (!user || user.disabledAt) {
31 throw new UnauthorizedException('Account is no longer active');
32 }
33 
34 return { id: user.id, email: user.email, role: user.role };
35 }
36}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Passport handles signature and expiry verification before your validate method ever runs.
  2. 2Re-loading the user on each request lets you revoke access even while a token is still valid.
  3. 3Whatever validate returns becomes the request user, so return only the fields your app needs.

Related explainers

typescript
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http';
import { BehaviorSubject, Observable, throwError } from 'rxjs';
import { catchError, filter, take, switchMap } from 'rxjs/operators';

Refreshing auth tokens in an Angular interceptor

http-interceptor token-refresh rxjs
Advanced 8 steps
go
package auth
 
import (
	"net/http"

Setting and reading secure session cookies in Go

cookies session-management security
Intermediate 6 steps
typescript
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import { GqlExecutionContext } from '@nestjs/graphql';
import { Reflector } from '@nestjs/core';
import { JwtService } from '@nestjs/jwt';

How a GraphQL auth guard works in NestJS

authentication authorization jwt
Intermediate 7 steps
python
import os
from datetime import timedelta
 
 

Class-based config in a Flask app factory

configuration app-factory inheritance
Intermediate 7 steps
typescript
type ResizeCallback = (size: { width: number; height: number }) => void;
 
export function observeResize(callback: ResizeCallback, delay = 150) {
  let timeoutId: ReturnType<typeof setTimeout> | undefined;

Debouncing window resize in TypeScript

debounce closures event-listeners
Intermediate 6 steps
typescript
import { Injectable, Logger, OnApplicationShutdown } from '@nestjs/common';
import { InjectRedis } from '@nestjs-modules/ioredis';
import Redis from 'ioredis';
import { DataSource } from 'typeorm';

Graceful shutdown hooks in NestJS

graceful-shutdown lifecycle-hooks dependency-injection
Intermediate 7 steps

Share this explainer

Here's the card — post it anywhere.

How a JWT strategy authenticates in NestJS — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code