// src/auth/jwt.guard.ts import { CanActivate, ExecutionContext, Injectable, UnauthorizedException, ForbiddenException, } from '@nestjs/common'; import { Reflector } from '@nestjs/core'; import { IdentityProviderName, JwtService } from './jwt.service'; import { decodeJwt } from 'jose'; import { METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED } from './allow-public-access.decorator'; @Injectable() export class JwtAuthGuard implements CanActivate { constructor( private readonly reflector: Reflector, private readonly jwtService: JwtService, ) {} async canActivate(context: ExecutionContext): Promise { const isPublicAccessAllowed = this.reflector.getAllAndOverride(METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED, [ context.getHandler(), context.getClass(), ]); if (isPublicAccessAllowed) return true; const request = context.switchToHttp().getRequest(); const authz = request.headers?.authorization as string | undefined; if (!authz || !authz.startsWith('Bearer ')) { throw new UnauthorizedException('Missing or invalid Authorization header'); } const token = authz.slice('Bearer '.length).trim(); if (!token) { throw new UnauthorizedException('Empty bearer token'); } // let identityProvider = // this.reflector.getAllAndOverride(IDP_KEY, [ // context.getHandler(), // context.getClass(), // ]); // if (!identityProvider) { // } let identityProvider: IdentityProviderName; try { const { iss } = decodeJwt(token) as { iss?: string }; if (!iss) { throw new UnauthorizedException('Token has no issuer (iss) claim'); } identityProvider = this.pickIdPFromIssuer(iss); } catch (e) { throw new UnauthorizedException( e instanceof Error ? e.message : 'Unable to decode token', ); } try { const verifyResult = await this.jwtService.verify(token, identityProvider); request.user = verifyResult.payload; request.tokenHeader = verifyResult.protectedHeader; request.identityProvider = identityProvider; return true; } catch (e) { const msg = e instanceof Error ? e.message : 'JWT verification failed'; // iss/aud 불일치는 보통 401, 접근권한 이슈는 403 (여기선 401로 통일) throw new UnauthorizedException(msg); } } /** * issuer(iss)로부터 IdP 추정 * - Entra ID: https://login.microsoftonline.com//v2.0 * - Cognito: https://cognito-idp..amazonaws.com/ */ private pickIdPFromIssuer(issuer: string): IdentityProviderName { const lower = issuer.toLowerCase(); if (lower.includes('login.microsoftonline.com')) { return 'MICROSOFT_ENTRAID'; } if (lower.includes('cognito-idp.') && lower.includes('.amazonaws.com')) { return 'AMAZON_COGNITO'; } // 필요하다면 여기서 jwtService 내부에 등록된 issuer들로 엄격 매칭하도록 변경 가능: // const configuredIssuers = this.jwtService.getConfiguredIssuers?.(); // ... throw new ForbiddenException(`Unknown issuer: ${issuer}`); } }