From f4c21e3c506d357b7b8ec9dc77ced97ac079f9b2 Mon Sep 17 00:00:00 2001 From: andres Date: Sat, 12 Aug 2023 18:47:40 +0200 Subject: [PATCH] add short lived access token --- src/modules/auth/auth.controller.ts | 5 ++++- src/modules/auth/auth.service.ts | 2 +- src/modules/auth/use-cases/refresh-token-use-case.ts | 8 +++++--- 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/src/modules/auth/auth.controller.ts b/src/modules/auth/auth.controller.ts index 74074e4..67d13e5 100644 --- a/src/modules/auth/auth.controller.ts +++ b/src/modules/auth/auth.controller.ts @@ -190,7 +190,10 @@ export class AuthController { ): Promise { if (!req.cookies?.refreshToken) throw new UnauthorizedException() const userId = req.user.id - const newTokens = await this.commandBus.execute(new RefreshTokenCommand(userId)) + const shortAccessToken = req.headers['x-short-access-token'] === 'true' + const newTokens = await this.commandBus.execute( + new RefreshTokenCommand(userId, shortAccessToken) + ) res.cookie('refreshToken', newTokens.refreshToken, { httpOnly: true, diff --git a/src/modules/auth/auth.service.ts b/src/modules/auth/auth.service.ts index 2de56f0..a95ef5e 100644 --- a/src/modules/auth/auth.service.ts +++ b/src/modules/auth/auth.service.ts @@ -16,7 +16,7 @@ export class AuthService { const accessSecretKey = process.env.ACCESS_JWT_SECRET_KEY const refreshSecretKey = process.env.REFRESH_JWT_SECRET_KEY - const accessExpiresIn = rememberMe ? '1d' : '10m' + const accessExpiresIn = rememberMe ? '1d' : '10s' const payload: { userId: string; date: Date } = { userId, diff --git a/src/modules/auth/use-cases/refresh-token-use-case.ts b/src/modules/auth/use-cases/refresh-token-use-case.ts index a1f6eb7..19befac 100644 --- a/src/modules/auth/use-cases/refresh-token-use-case.ts +++ b/src/modules/auth/use-cases/refresh-token-use-case.ts @@ -5,7 +5,7 @@ import * as jwt from 'jsonwebtoken' import { AuthRepository } from '../infrastructure/auth.repository' export class RefreshTokenCommand { - constructor(public readonly userId: string) {} + constructor(public readonly userId: string, public readonly shortAccessToken: boolean) {} } @CommandHandler(RefreshTokenCommand) @@ -13,7 +13,7 @@ export class RefreshTokenHandler implements ICommandHandler constructor(private readonly authRepository: AuthRepository) {} async execute(command: RefreshTokenCommand) { - const { userId } = command + const { userId, shortAccessToken } = command const accessSecretKey = process.env.ACCESS_JWT_SECRET_KEY const refreshSecretKey = process.env.REFRESH_JWT_SECRET_KEY @@ -22,7 +22,9 @@ export class RefreshTokenHandler implements ICommandHandler userId, date: new Date(), } - const accessToken = jwt.sign(payload, accessSecretKey, { expiresIn: '10m' }) + const accessToken = jwt.sign(payload, accessSecretKey, { + expiresIn: shortAccessToken ? '10s' : '10m', + }) const refreshToken = jwt.sign(payload, refreshSecretKey, { expiresIn: '30d', })