101 lines
2.7 KiB
TypeScript
101 lines
2.7 KiB
TypeScript
import { Injectable } from '@nestjs/common';
|
|
import {
|
|
createRemoteJWKSet,
|
|
jwtVerify,
|
|
JWTPayload,
|
|
JWTVerifyGetKey,
|
|
JWTVerifyResult,
|
|
} from 'jose';
|
|
import { SecretService } from '../global/secret/secret.service';
|
|
|
|
export type IdentityProviderName = 'MICROSOFT_ENTRAID';
|
|
|
|
interface EntraConfig {
|
|
tenantId: string;
|
|
audience: string;
|
|
issuer: string;
|
|
allowedAlgs: string[];
|
|
jwks: JWTVerifyGetKey;
|
|
}
|
|
|
|
@Injectable()
|
|
export class JwtService {
|
|
private entraConfig?: EntraConfig;
|
|
private readonly clockTolerance = Number(
|
|
process.env.JWT_CLOCK_TOLERANCE || 5,
|
|
);
|
|
|
|
constructor(private readonly secretService: SecretService) {}
|
|
|
|
public async verify(
|
|
token: string,
|
|
identityProvider: IdentityProviderName,
|
|
): Promise<JWTVerifyResult<JWTPayload>> {
|
|
if (!token) {
|
|
throw new Error('Empty token');
|
|
}
|
|
|
|
if (identityProvider !== 'MICROSOFT_ENTRAID') {
|
|
throw new Error(`Identity provider not configured: ${identityProvider}`);
|
|
}
|
|
|
|
const provider = await this.getEntraConfig();
|
|
const result = await jwtVerify(token, provider.jwks, {
|
|
issuer: provider.issuer,
|
|
audience: provider.audience,
|
|
algorithms: provider.allowedAlgs,
|
|
clockTolerance: this.clockTolerance,
|
|
});
|
|
|
|
const { payload, protectedHeader } = result;
|
|
if (!provider.allowedAlgs.includes(protectedHeader.alg as string)) {
|
|
throw new Error(`Unexpected alg: ${protectedHeader.alg}`);
|
|
}
|
|
if (payload.ver && payload.ver !== '2.0') {
|
|
throw new Error(`Unsupported Entra token version: ${payload.ver}`);
|
|
}
|
|
if (payload.tid && payload.tid !== provider.tenantId) {
|
|
throw new Error(`Unexpected tenant: ${payload.tid}`);
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
private async getEntraConfig(): Promise<EntraConfig> {
|
|
if (this.entraConfig) return this.entraConfig;
|
|
|
|
await this.secretService.ready();
|
|
const [audience, tenantId, allowedAlgsRaw] = await Promise.all([
|
|
this.secretService.get<string>('JWT_CLAIM_AUDIENCE'),
|
|
this.secretService.get<string>('MICROSOFT_ENTRAID_TENANT_ID'),
|
|
this.secretService.get<string>('MICROSOFT_ENTRAID_ALLOWED_ALGS', 'RS256'),
|
|
]);
|
|
|
|
const allowedAlgs = allowedAlgsRaw
|
|
.split(',')
|
|
.map((alg) => alg.trim())
|
|
.filter(Boolean);
|
|
if (allowedAlgs.length === 0) {
|
|
allowedAlgs.push('RS256');
|
|
}
|
|
|
|
const issuer = `https://login.microsoftonline.com/${tenantId}/v2.0`;
|
|
const jwks = createRemoteJWKSet(
|
|
new URL('https://login.microsoftonline.com/common/discovery/v2.0/keys'),
|
|
{
|
|
cooldownDuration: 30_000,
|
|
timeoutDuration: 10_000,
|
|
},
|
|
);
|
|
|
|
this.entraConfig = {
|
|
tenantId,
|
|
audience,
|
|
issuer,
|
|
allowedAlgs,
|
|
jwks,
|
|
};
|
|
return this.entraConfig;
|
|
}
|
|
}
|