NestJS course ยท Module 4: Authentication
Refresh Tokens - renewing legion passes
In this lesson9
The access token from the previous lessons lives for 15 minutes. A legionary who gets thrown out of the system every quarter of an hour will soon start cursing Architect Vitruvius. Stretching the pass to a week, on the other hand, is an open invitation to thieves: a JWT stays valid until its expiry date, so a stolen token opens the fort for seven days and cannot easily be revoked. The way out is two tokens with different jobs.
What are Refresh Tokens?
Imagine the pass system in a legionary camp. A legionary receives two documents:
- Access Token (a short sentry pass) - lets him into the camp and expires after about a quarter of an hour
- Refresh Token (the centurion's seal) - lives for several days and lets him obtain a new pass without standing before the tribunal again
Why do we need two tokens?
- Security - if someone intercepts the access token, they have access only for a short time
- Convenience - the user does not have to log in every quarter of an hour
- Control - we can invalidate the refresh token, blocking access renewal
The refresh token mechanism is the foundation of secure authentication systems in production applications.
Generating a token pair
We sign the two tokens with separate secrets, JWT_ACCESS_SECRET and JWT_REFRESH_SECRET, so neither can be forged or used in place of the other. This is the login:
// auth/auth.service.ts
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';
import { createHash } from 'node:crypto';
@Injectable()
export class AuthService {
constructor(
private jwtService: JwtService,
private configService: ConfigService,
private usersService: UsersService,
) {}
async login(loginDto: LoginDto): Promise<TokenPair> {
const user = await this.usersService.validateCredentials(
loginDto.username,
loginDto.password,
);
if (!user) {
throw new UnauthorizedException('Invalid login credentials, legionary!');
}
// Generate a token pair
const tokens = await this.generateTokenPair(user);
// Store the SHA-256 digest of the refresh token, not the token itself
const hashedRefreshToken = this.hashToken(tokens.refreshToken);
await this.usersService.updateRefreshToken(user.id, hashedRefreshToken);
return tokens;
}validateCredentials() checks the password with bcrypt.compare() from the hashing lesson. Only the digest of the refresh token lands in the database - we store the access token nowhere, because it expires within a quarter of an hour anyway. You will meet the UserDocument type in a moment, with the schema.
A separate method creates the token pair:
async generateTokenPair(user: UserDocument): Promise<TokenPair> {
const payload = {
sub: user.id,
username: user.username,
role: user.role,
cohort: user.cohortName,
};
const [accessToken, refreshToken] = await Promise.all([
this.jwtService.signAsync(payload, {
secret: this.configService.get('JWT_ACCESS_SECRET'),
expiresIn: '15m', // Short sentry pass - 15 minutes
}),
this.jwtService.signAsync(payload, {
secret: this.configService.get('JWT_REFRESH_SECRET'),
expiresIn: '7d', // Centurion's seal - longer lifetime
}),
]);
return { accessToken, refreshToken };
}
// Refresh token digest: SHA-256, because bcrypt reads only 72 bytes
private hashToken(token: string): string {
return createHash('sha256').update(token).digest('hex');
}
}signAsync() takes a secret and an expiresIn for each token separately, and Promise.all() signs both in parallel. The payload is the same; only the secret and the lifetime differ. Notice hashToken(): it deliberately uses SHA-256, not bcrypt. bcrypt reads only 72 bytes, and two JWTs of the same legionary share an identical beginning (the header and the first payload fields), so bcrypt.compare(oldToken, hashOfNewOne) would return true. The token is long and random, so a fast digest is more than enough.
One thing outside this file: JwtStrategy must verify access tokens with the same secret you sign them with. If you introduce JWT_ACCESS_SECRET, change its secretOrKey as well.
The token renewal endpoint
The controller exposes three routes: login, refresh and logout:
// auth/auth.controller.ts
@Controller('auth')
export class AuthController {
constructor(private authService: AuthService) {}
@Post('login')
async login(@Body() loginDto: LoginDto) {
return this.authService.login(loginDto);
}
@Post('refresh')
async refreshTokens(@Body('refreshToken') refreshToken: string) {
return this.authService.refreshTokens(refreshToken);
}
@Post('logout')
@UseGuards(JwtAuthGuard)
async logout(@Req() req) {
// Invalidate refresh token on logout
await this.authService.logout(req.user.userId);
return { message: 'Legionary logged out successfully' };
}
}/auth/refresh has no JwtAuthGuard, because we call it precisely when the access token has expired - the refresh token itself is the credential here. Logout is protected, and req.user.userId comes from JwtStrategy, whose validate() returns { userId, username, role }.
Renewal logic in the service
The refreshTokens() method starts by checking whether the seal is genuine and whose document it is:
// auth/auth.service.ts (continued)
async refreshTokens(refreshToken: string): Promise<TokenPair> {
// 1. Verify the refresh token
let payload;
try {
payload = await this.jwtService.verifyAsync(refreshToken, {
secret: this.configService.get('JWT_REFRESH_SECRET'),
});
} catch (error) {
throw new UnauthorizedException("Centurion's seal has expired - log in again!");
}
// 2. Find the user and check the stored refresh token
const user = await this.usersService.findById(payload.sub);
if (!user || !user.hashedRefreshToken) {
throw new UnauthorizedException('Access denied!');
}verifyAsync() with the refresh secret checks the signature and the expiry date. A missing stored digest means the legionary logged out or his session was revoked.
Next we compare the token with the database and issue a new pair:
// 3. Compare the token's digest with the stored one
const isTokenValid = this.hashToken(refreshToken) === user.hashedRefreshToken;
if (!isTokenValid) {
// Potential token theft - invalidate all sessions
await this.usersService.updateRefreshToken(user.id, null);
throw new UnauthorizedException('Token invalidated - suspicious activity detected!');
}
// 4. Generate a new token pair (Token Rotation)
const newTokens = await this.generateTokenPair(user);
// 5. Save the new refresh token
const hashedNewRefreshToken = this.hashToken(newTokens.refreshToken);
await this.usersService.updateRefreshToken(user.id, hashedNewRefreshToken);
return newTokens;
}
async logout(userId: string): Promise<void> {
// Invalidate the refresh token
await this.usersService.updateRefreshToken(userId, null);
}If the digest does not match, someone brought a correctly signed but outdated token - a sign of theft, so we erase the stored digest and everyone has to log in again. logout() does the same at the user's request.
Token Rotation
A key security technique: on every refresh we generate a new refresh token and invalidate the old one. If someone steals a refresh token and tries to use it after the rotation, we will detect it:
// Token theft protection scheme
// 1. Legionary logs in -> receives AT1 + RT1
// 2. AT1 expires -> sends RT1 -> receives AT2 + RT2 (RT1 invalidated)
// 3. Thief tries to use RT1 -> DENIED (token already rotated)
// 4. System detects use of old token -> invalidates ALL user sessionsThe old RT1 still has a valid signature and expiry date. Only the comparison with the digest in the database rejects it - and that is why we keep the digest.
User schema with a refresh token
The digest goes into the hashedRefreshToken field of the Mongoose schema:
// users/user.schema.ts (Mongoose)
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { HydratedDocument } from 'mongoose';
@Schema({ timestamps: true })
export class User {
@Prop({ required: true, unique: true })
username: string;
@Prop({ required: true })
password: string;
@Prop()
email: string;
@Prop({ default: 'miles' })
role: string;
@Prop({ type: String, default: null })
hashedRefreshToken: string | null;
@Prop()
cohortName: string;
}
export type UserDocument = HydratedDocument<User>;
export const UserSchema = SchemaFactory.createForClass(User);The nullable option comes from TypeORM, and Mongoose simply ignores it. Here null is allowed by default, and with the string | null type you have to state type: String explicitly. HydratedDocument<User> is the pattern from the current NestJS documentation: the class describes the fields, and the document type adds id and the Mongoose methods.
Refresh Token Guard
Instead of verifying the token by hand, you can hand the job to Passport. A strategy named 'jwt-refresh' reads the token from a body field:
// auth/guards/refresh-token.guard.ts
import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class RefreshTokenGuard extends AuthGuard('jwt-refresh') {}
// auth/strategies/refresh-token.strategy.ts
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { ConfigService } from '@nestjs/config';
import { Request } from 'express';
@Injectable()
export class RefreshTokenStrategy extends PassportStrategy(Strategy, 'jwt-refresh') {
constructor(private configService: ConfigService) {
super({
jwtFromRequest: ExtractJwt.fromBodyField('refreshToken'),
secretOrKey: configService.getOrThrow('JWT_REFRESH_SECRET'),
passReqToCallback: true,
});
}
validate(req: Request, payload: any) {
const refreshToken = req.body.refreshToken;
return { ...payload, refreshToken };
}
}passReqToCallback: true passes the whole request to validate(), so the raw token ends up in req.user.refreshToken. The strategy only checks the signature and the date, which is why the comparison with the database digest stays in the service anyway. On the client, keep the refresh token in an httpOnly cookie that JavaScript cannot read - that is my recommendation.
Practical exercise
Implement a complete refresh token system for the legion, step by step:
// Your code here
// 1. Configure two JWT secrets (access and refresh) in ConfigService
// 2. Implement the POST /auth/refresh endpoint with validation
// 3. Add Token Rotation on each refresh
// 4. Implement detection of reused old tokens
// 5. Add cleanup of expired tokens (cron job)For cleaning up old entries, @nestjs/schedule with its @Cron() decorator comes in handy.
Summary
You have been appointed guardian of the Empire's gates! Now you can:
- Generate token pairs - access token (short) + refresh token (long)
- Implement Token Rotation - a new refresh token on every refresh
- Detect token theft - invalidating sessions when an old token is reused
- Store refresh tokens safely in the database as a SHA-256 digest
- Implement logout - invalidating the refresh token on logout
- Create Passport Strategies for refresh tokens
In the next lesson we will take on OAuth and logging in with Google.
Remember: the sentry pass must be short and the centurion's seal single-use, because every rotation closes the road to whoever stole the previous one.
Code for this lesson: src/auth/refresh-tokens.ts
// Refresh Tokens - Renewing the legion's passes
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';
interface TokenPair {
accessToken: string;
refreshToken: string;
}
interface JwtPayload {
sub: string;
username: string;
role: string;
}
@Injectable()
export class RefreshTokenService {
constructor(
private jwtService: JwtService,
private configService: ConfigService,
) {}
// TODO: Implement token pair generation
// accessToken - short lifetime (15m)
// refreshToken - long lifetime (7d)
async generateTokenPair(payload: JwtPayload): Promise<TokenPair> {
// TODO: Generate accessToken
const accessToken = this.jwtService.sign(payload, {
secret: '', // TODO: fetch JWT_ACCESS_SECRET from configService
expiresIn: '', // TODO: set to '15m'
});
// TODO: Generate refreshToken with a different secret
const refreshToken = this.jwtService.sign(payload, {
secret: '', // TODO: fetch JWT_REFRESH_SECRET from configService
expiresIn: '', // TODO: set to '7d'
});
return { accessToken, refreshToken };
}
// TODO: Implement token refresh
async refreshTokens(oldRefreshToken: string): Promise<TokenPair> {
try {
// TODO: Verify old refreshToken
const payload = this.jwtService.verify(oldRefreshToken, {
secret: '', // TODO: same secret as during generation refresh
});
// TODO: Generate new token pair
const newPayload: JwtPayload = {
sub: payload.sub,
username: payload.username,
role: payload.role,
};
return this.generateTokenPair(newPayload);
} catch (error) {
throw new UnauthorizedException('Refresh token expired or is invalid!');
}
}
}
console.log('Access Token: short lifetime (15 minutes)');
console.log('Refresh Token: long lifetime (7 days)');
console.log('Token rotation increases security');
Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What is the typical difference in lifetime between an Access Token and a Refresh Token?
Hands-on tasks in the game
- Vertical ordering
Arrange the steps of JWT token refresh: