|
1 | | -import { Injectable, UnauthorizedException } from "@nestjs/common"; |
| 1 | +import { |
| 2 | + ForbiddenException, |
| 3 | + Injectable, |
| 4 | + Logger, |
| 5 | + UnauthorizedException, |
| 6 | +} from "@nestjs/common"; |
2 | 7 | import { ConfigService } from "@nestjs/config"; |
3 | 8 | import { JwtService } from "@nestjs/jwt"; |
4 | 9 | import jwksClient from "jwks-rsa"; |
@@ -61,20 +66,20 @@ export class AuthService { |
61 | 66 | publicKey: key, |
62 | 67 | algorithms: ["RS256"], |
63 | 68 | }) as KeycloakUser; |
64 | | - |
| 69 | + console.info("payload", payload); |
65 | 70 | // Validate audience claim |
66 | 71 | await this.validateAudience(payload); |
67 | 72 | // validate role |
68 | 73 | if (!payload.client_roles) { |
69 | | - throw new UnauthorizedException("Token missing client roles"); |
| 74 | + throw new ForbiddenException("Token missing client roles"); |
70 | 75 | } |
71 | | - if (this.hasRole(payload, "ai-poc-participant")) { |
72 | | - throw new UnauthorizedException("User does not have the required role"); |
| 76 | + if (!this.hasRole(payload, "ai-poc-participant")) { |
| 77 | + throw new ForbiddenException("User does not have the required role"); |
73 | 78 | } |
74 | 79 | return payload; |
75 | 80 | } catch (error) { |
76 | 81 | console.error("Token validation error:", error); |
77 | | - throw new UnauthorizedException("Invalid or expired token"); |
| 82 | + throw error; |
78 | 83 | } |
79 | 84 | } |
80 | 85 |
|
@@ -116,6 +121,10 @@ export class AuthService { |
116 | 121 |
|
117 | 122 | hasRole(user: KeycloakUser, role: string): boolean { |
118 | 123 | // Check realm roles |
| 124 | + if (!Array.isArray(user.client_roles)) { |
| 125 | + console.info("User has no client roles is not array"); |
| 126 | + return false; |
| 127 | + } |
119 | 128 | if (user.client_roles?.includes(role)) { |
120 | 129 | return true; |
121 | 130 | } |
|
0 commit comments