feat(auth): implement OIDC JWT verification with dynamic identity provider support

- Added JwtService (azure-jwt.service.ts) to verify tokens from multiple IdPs (Microsoft Entra ID, Amazon Cognito)
- Implemented dynamic provider configuration (issuer, audience, jwksUri)
- Added JwtAuthGuard for NestJS to handle JWT validation via jose library
- Integrated @Public() and @IdP() decorators for route-level control
- Audience () and issuer () validation logic aligned with OIDC standards
- Added clock tolerance and allowed algorithm checks for security hardening
This commit is contained in:
dahyeon committed 2025-11-08 03:33:36 +00:00
1 parent 02255d7240
commit d6b9477094
14 files changed
+346 -47

No files matched your search

+7 -3
View File
@@ -1,12 +1,16 @@
import { Controller, Get } from '@nestjs/common';
import { Controller, Get, UseGuards } from '@nestjs/common';
import { AppService } from './app.service';
import { JwtAuthGuard } from './modules/global/auth/jwt.guard';
import { AllowPublicAccess } from './modules/global/auth/allow-public-access.decorator';
@UseGuards(JwtAuthGuard)
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@AllowPublicAccess()
@Get()
getHello(): string {
return this.appService.getHello();
isHealthy(): string {
return this.appService.isHealthy();
}
}
+3 -1
View File
@@ -3,6 +3,7 @@ import { AppController } from './app.controller';
import { AppService } from './app.service';
import { GlobalModule } from './modules/global/global.module';
import { ConfigModule } from '@nestjs/config';
import { AccountModule } from './modules/account/account.module';
@Module({
imports: [
@@ -10,7 +11,8 @@ import { ConfigModule } from '@nestjs/config';
isGlobal: true,
envFilePath: process.env.NODE_ENV === 'prod' ? '.env.prod' : process.env.NODE_ENV === 'test' ? '.env.test' : '.env.dev',
}),
GlobalModule],
GlobalModule,
AccountModule],
controllers: [AppController],
providers: [AppService],
})
+5 -2
View File
@@ -2,7 +2,10 @@ import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
// getHello(): string {
// return 'Hello World!';
// }
isHealthy(): string {
return 'OK';
}
}
+17 -13
View File
@@ -5,20 +5,24 @@ import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const apiVersion = 1;
const config = new DocumentBuilder()
.setTitle('Cats example')
.setDescription('The cats API description')
.setVersion('1.0')
.addTag('cats')
.build();
const options: SwaggerCustomOptions = {
ui: false, // Swagger UI is disabled
raw: ['yaml'], // JSON API definition is still accessible (YAML is disabled)
}
const documentFactory = () => SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api', app, documentFactory, options);
if (process.env.NODE_ENV === 'dev' || process.env.NODE_ENV === 'test') {
const config = new DocumentBuilder()
.setTitle('Gemwiki API')
.setDescription('The Gemwiki API description')
.setVersion('1.0')
.addTag('gemwiki')
.build();
const options: SwaggerCustomOptions = {
ui: false,
raw: ['yaml'],
}
const documentFactory = () => SwaggerModule.createDocument(app, config);
SwaggerModule.setup(`v${apiVersion}/api`, app, documentFactory, options);
}
await app.listen(process.env.PORT ?? 3000);
app.setGlobalPrefix(`v${apiVersion}`);
await app.listen(process.env.PORT ?? 3415);
}
bootstrap();
+20
View File
@@ -0,0 +1,20 @@
import { Controller, Get, UseGuards } from "@nestjs/common";
import { AccountService } from "./account.service";
import { JwtAuthGuard } from "../global/auth/jwt.guard";
@Controller('account')
export class AccountController {
constructor(private readonly accountService: AccountService) {}
@Get('signin')
signIn(): string {
return this.accountService.signIn();
}
@Get()
@UseGuards(JwtAuthGuard)
getAccountInfo(): string {
return this.accountService.getAccountInfo();
}
}
+9
View File
@@ -0,0 +1,9 @@
import { Module } from "@nestjs/common";
import { AccountController } from "./account.controller";
import { AccountService } from "./account.service";
@Module({
controllers: [AccountController],
providers: [AccountService],
})
export class AccountModule {}
+12
View File
@@ -0,0 +1,12 @@
import { Injectable } from "@nestjs/common";
@Injectable()
export class AccountService {
signIn(): string {
return 'Sign In Successful';
}
getAccountInfo(): string {
return 'Account Information';
}
}
@@ -0,0 +1,4 @@
// auth/public.decorator.ts
import { SetMetadata } from '@nestjs/common';
export const METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED = 'IS_PUBLIC_ACCESS_ALLOWED';
export const AllowPublicAccess = () => SetMetadata(METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED, true);
+96
View File
@@ -0,0 +1,96 @@
// 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<boolean> {
const isPublicAccessAllowed = this.reflector.getAllAndOverride<boolean>(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<IdentityProviderName>(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/<tenant>/v2.0
* - Cognito: https://cognito-idp.<region>.amazonaws.com/<userPoolId>
*/
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}`);
}
}
+137
View File
@@ -0,0 +1,137 @@
// src/auth/azure-jwt.service.ts
import { Injectable, OnModuleInit } from '@nestjs/common';
import { SecretService } from '../secret/secret.service';
import {
createRemoteJWKSet,
jwtVerify,
JWTPayload,
JWTVerifyResult,
} from 'jose';
/**
* Microsoft Entra ID 를 IdP로 사용하는 OpenID Connect 인증 관련 모듈.
* OIDC 인증 흐름 -> https://learn.microsoft.com/ko-kr/entra/architecture/auth-oidc 문서 참조.
* 추후 IdP 확장 고려해 IdP 별로 해당 IdP 이름을 접두사에 붙인다.
*/
export type IdentityProviderName = 'MICROSOFT_ENTRAID' | 'AMAZON_COGNITO';
// export type IdentityProvider = {
// [x in IdentityProviderName]: EntraIDIdentityProviderMetadata
// };
// export type EntraIDIdentityProviderMetadata = {
// issuer: string;
// authorizationEndpoint: string;
// tokenEndpoint: string;
// userInfoEndpoint: string;
// jwksUri: string;
// }
@Injectable()
export class JwtService implements OnModuleInit {
private jwtClaimAudience: string;
private MICROSOFT_ENTRAID_tenantId: string;
private MICROSOFT_ENTRAID_allowedAlgs: string;
private MICROSOFT_ENTRAID_issuer: string;
private MICROSOFT_ENTRAID_jwksUri: string;
private MICROSOFT_ENTRAID_jwks: ReturnType<typeof createRemoteJWKSet>;
private readonly tokenSigningAlgValuesSupported = ['RS256'];
private readonly clockTolerance =
Number(process.env.JWT_CLOCK_TOLERANCE || 5); // seconds
constructor(
private readonly secretService: SecretService
) {}
public async onModuleInit() {
await this.secretService.ready()
this.jwtClaimAudience = await this.secretService.get('JWT_CLAIM_AUDIENCE')
this.MICROSOFT_ENTRAID_tenantId = await this.secretService.get('MICROSOFT_ENTRAID_TENANT_ID')
this.MICROSOFT_ENTRAID_allowedAlgs = await this.secretService.get('MICROSOFT_ENTRAID_ALLOWED_ALGS')
this.MICROSOFT_ENTRAID_issuer = `https://login.microsoftonline.com/${this.MICROSOFT_ENTRAID_tenantId}/v2.0`;
this.MICROSOFT_ENTRAID_jwksUri = `https://login.microsoftonline.com/${this.MICROSOFT_ENTRAID_tenantId}/discovery/v2.0/keys`;
this.MICROSOFT_ENTRAID_jwks = createRemoteJWKSet(new URL(this.MICROSOFT_ENTRAID_jwksUri), {
// cache: true,
cooldownDuration: 30_000, // 30s
timeoutDuration: 10_000, // 10s
});
}
/**
* Authorization: Bearer <token> 의 <token> 부분을 검증.
* - iss: v2.0 발급자
* - aud: Application ID URI와 정확히 일치해야 함
* - alg: RS256(기본)
*/
async verify(
token: string,
identityProvider: IdentityProviderName
): Promise<JWTVerifyResult<JWTPayload>> {
if (!token) {
throw new Error('Empty token');
}
// IdP별 설정 매핑
const providers = {
MICROSOFT_ENTRAID: {
jwks: this.MICROSOFT_ENTRAID_jwks,
issuer: this.MICROSOFT_ENTRAID_issuer,
audience: this.jwtClaimAudience,
extraValidate: (payload: JWTPayload) => {
// AAD v2 토큰 전용 추가 검증
if (payload['ver'] && payload['ver'] !== '2.0') {
throw new Error(`Unsupported AAD token version: ${payload['ver']}`);
}
if (payload['tid'] && payload['tid'] !== this.MICROSOFT_ENTRAID_tenantId) {
throw new Error(`Unexpected tenant: ${payload['tid']}`);
}
},
},
AMAZON_COGNITO: {
// 아래 3개 필드는 onModuleInit에서 Entra와 동일하게 준비해야 함
// this.AMAZON_COGNITO_jwks = createRemoteJWKSet(new URL(this.AMAZON_COGNITO_jwksUri), {...})
jwks: this['AMAZON_COGNITO_jwks'],
issuer: this['AMAZON_COGNITO_issuer'],
audience: this['AMAZON_COGNITO_audience'],
extraValidate: (payload: JWTPayload) => {
// 필요하면 Cognito 전용 검증(예: token_use, cognito:username 등) 추가
// if (payload['token_use'] && payload['token_use'] !== 'id' /* or 'access' */) { ... }
},
},
} as const;
const provider = providers[identityProvider];
if (!provider?.jwks || !provider?.issuer || !provider?.audience) {
throw new Error(`Identity provider not configured: ${identityProvider}`);
}
// 허용 알고리즘: 환경변수(콤마 구분) -> 기본값(['RS256'])
const allowedAlgs =
(this.MICROSOFT_ENTRAID_allowedAlgs
? this.MICROSOFT_ENTRAID_allowedAlgs.split(',').map(s => s.trim()).filter(Boolean)
: this.tokenSigningAlgValuesSupported) as string[];
const result = await jwtVerify(token, provider.jwks, {
issuer: provider.issuer,
audience: provider.audience,
algorithms: allowedAlgs,
clockTolerance: this.clockTolerance,
});
const { payload, protectedHeader } = result;
// 공통: alg 확인
if (!allowedAlgs.includes(protectedHeader.alg as string)) {
throw new Error(`Unexpected alg: ${protectedHeader.alg}`);
}
// 프로바이더별 추가 검증
provider.extraValidate?.(payload);
return result;
}
}
+4 -3
View File
@@ -1,12 +1,13 @@
import { Module, Global } from '@nestjs/common';
import { SecretModule } from './secret/secret.module';
import { DatabaseModule } from './database/database.module';
// import { DatabaseModule } from './database/database.module';
import { NatsModule } from './nats/nats.module';
import { JwtService } from './auth/jwt.service';
@Global()
@Module({
imports: [SecretModule, NatsModule],
providers: [],
exports: [SecretModule, NatsModule],
providers: [JwtService],
exports: [SecretModule, NatsModule, JwtService],
})
export class GlobalModule {}