Skip to content
This repository was archived by the owner on Jan 28, 2026. It is now read-only.

Commit 5c2a907

Browse files
committed
feat: Enhance JwtAuthGuard to provide detailed UnauthorizedException messages
1 parent 1f63da8 commit 5c2a907

1 file changed

Lines changed: 23 additions & 2 deletions

File tree

src/auth/guards/jwt-auth.guard.ts

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { ExecutionContext, Injectable } from '@nestjs/common';
1+
import { ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
22
import { Reflector } from '@nestjs/core';
33
import { AuthGuard } from '@nestjs/passport';
44
import { IS_PUBLIC_KEY } from '../decorators/public.decorator';
@@ -29,9 +29,30 @@ export class JwtAuthGuard extends AuthGuard('jwt') {
2929
if (isPublic) {
3030
return user || null;
3131
}
32+
33+
// Если есть ошибка или пользователь отсутствует
3234
if (err || !user) {
33-
throw err || new Error('Unauthorized');
35+
// Если ошибка уже является HttpException (например, UnauthorizedException из JwtStrategy), пробрасываем её
36+
if (err && (err.statusCode || err instanceof UnauthorizedException)) {
37+
throw err;
38+
}
39+
40+
// Определяем сообщение об ошибке
41+
let message = 'Необходима авторизация';
42+
if (info?.message) {
43+
message = info.message;
44+
} else if (info?.name === 'JsonWebTokenError') {
45+
message = 'Недействительный токен';
46+
} else if (info?.name === 'TokenExpiredError') {
47+
message = 'Токен истёк';
48+
} else if (!user && !err) {
49+
message = 'Токен не предоставлен или недействителен';
50+
}
51+
52+
// Всегда выбрасываем UnauthorizedException для корректного статуса 401
53+
throw new UnauthorizedException(message);
3454
}
55+
3556
return user;
3657
}
3758
}

0 commit comments

Comments
 (0)