|
| 1 | +import { |
| 2 | + Injectable, |
| 3 | + CanActivate, |
| 4 | + ExecutionContext, |
| 5 | + UnauthorizedException, |
| 6 | + ForbiddenException, |
| 7 | +} from '@nestjs/common'; |
| 8 | +import { Request } from 'express'; |
| 9 | +import { Reflector } from '@nestjs/core'; |
| 10 | +import { ConfigService } from '@nestjs/config'; |
| 11 | +import * as jwt from 'jsonwebtoken'; |
| 12 | +import { JwksClient } from 'jwks-rsa'; |
| 13 | +import { IS_PUBLIC_KEY } from './public.decorator'; |
| 14 | + |
| 15 | +interface User { |
| 16 | + idir_username?: string; |
| 17 | + display_name?: string; |
| 18 | + email?: string; |
| 19 | + roles?: string[]; |
| 20 | + [key: string]: unknown; // Allow additional properties from JWT |
| 21 | +} |
| 22 | + |
| 23 | +declare module 'express' { |
| 24 | + interface Request { |
| 25 | + user?: User; |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +@Injectable() |
| 30 | +export class BCGovAuthGuard implements CanActivate { |
| 31 | + private jwksClient: JwksClient; |
| 32 | + |
| 33 | + constructor( |
| 34 | + private configService: ConfigService, |
| 35 | + private reflector: Reflector, |
| 36 | + ) { |
| 37 | + const ssoAuthServerUrl = this.configService.get<string>('SSO_AUTH_SERVER_URL'); |
| 38 | + |
| 39 | + // If SSO_AUTH_SERVER_URL includes the full OIDC path, extract the base realm URL |
| 40 | + let jwksUri: string; |
| 41 | + if (ssoAuthServerUrl.includes('/protocol/openid-connect')) { |
| 42 | + // SSO_AUTH_SERVER_URL is the full OIDC endpoint |
| 43 | + jwksUri = ssoAuthServerUrl.replace('/protocol/openid-connect', '') + '/protocol/openid-connect/certs'; |
| 44 | + } else { |
| 45 | + // SSO_AUTH_SERVER_URL is the base Keycloak URL |
| 46 | + const realm = this.configService.get<string>('SSO_REALM'); |
| 47 | + jwksUri = `${ssoAuthServerUrl}/realms/${realm}/protocol/openid-connect/certs`; |
| 48 | + } |
| 49 | + |
| 50 | + this.jwksClient = new JwksClient({ |
| 51 | + jwksUri, |
| 52 | + cache: true, |
| 53 | + cacheMaxAge: 86400000, // 24 hours |
| 54 | + }); |
| 55 | + } |
| 56 | + |
| 57 | + async canActivate(context: ExecutionContext): Promise<boolean> { |
| 58 | + // Check if route is public |
| 59 | + const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [ |
| 60 | + context.getHandler(), |
| 61 | + context.getClass(), |
| 62 | + ]); |
| 63 | + |
| 64 | + if (isPublic) { |
| 65 | + return true; |
| 66 | + } |
| 67 | + |
| 68 | + const request = context.switchToHttp().getRequest<Request>(); |
| 69 | + const authHeader = request.headers['authorization']; |
| 70 | + |
| 71 | + if (!authHeader || !authHeader.startsWith('Bearer ')) { |
| 72 | + throw new UnauthorizedException('No Bearer token provided'); |
| 73 | + } |
| 74 | + |
| 75 | + const token = authHeader.substring(7); |
| 76 | + |
| 77 | + try { |
| 78 | + const user = await this.validateToken(token); |
| 79 | + // Attach user to request (like Express middleware does) |
| 80 | + request.user = user; |
| 81 | + return true; |
| 82 | + } catch { |
| 83 | + throw new ForbiddenException('Invalid token'); |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + private async validateToken(token: string): Promise<User> { |
| 88 | + try { |
| 89 | + // Decode token header to get key ID |
| 90 | + const decoded = jwt.decode(token, { complete: true }); |
| 91 | + if (!decoded || !decoded.header.kid) { |
| 92 | + throw new UnauthorizedException('Invalid token format'); |
| 93 | + } |
| 94 | + |
| 95 | + // Get signing key |
| 96 | + const key = await this.jwksClient.getSigningKey(decoded.header.kid); |
| 97 | + const signingKey = key.getPublicKey(); |
| 98 | + |
| 99 | + // Determine the correct issuer |
| 100 | + const ssoAuthServerUrl = this.configService.get<string>('SSO_AUTH_SERVER_URL'); |
| 101 | + let expectedIssuer: string; |
| 102 | + if (ssoAuthServerUrl.includes('/protocol/openid-connect')) { |
| 103 | + // SSO_AUTH_SERVER_URL is the full OIDC endpoint, issuer is the realm URL |
| 104 | + expectedIssuer = ssoAuthServerUrl.replace('/protocol/openid-connect', ''); |
| 105 | + } else { |
| 106 | + // SSO_AUTH_SERVER_URL is the base Keycloak URL |
| 107 | + const realm = this.configService.get<string>('SSO_REALM'); |
| 108 | + expectedIssuer = `${ssoAuthServerUrl}/realms/${realm}`; |
| 109 | + } |
| 110 | + |
| 111 | + // Verify and decode token |
| 112 | + const verified = jwt.verify(token, signingKey, { |
| 113 | + algorithms: ['RS256'], |
| 114 | + issuer: expectedIssuer, |
| 115 | + }); |
| 116 | + |
| 117 | + return verified as User; |
| 118 | + } catch { |
| 119 | + throw new UnauthorizedException('Token validation failed'); |
| 120 | + } |
| 121 | + } |
| 122 | +} |
0 commit comments