From fe6ee03099644cfa1b529d8add12bf4b9a7608d9 Mon Sep 17 00:00:00 2001 From: David Barrat Date: Sun, 12 Nov 2023 03:53:37 +0100 Subject: [PATCH] enable adhocJwks to verify tokens --- src/errors/messages.ts | 5 +++-- src/vendors/jwks/jwks.ts | 21 ++++++++++++--------- 2 files changed, 15 insertions(+), 11 deletions(-) diff --git a/src/errors/messages.ts b/src/errors/messages.ts index 14a6ebc..13d5c10 100644 --- a/src/errors/messages.ts +++ b/src/errors/messages.ts @@ -28,9 +28,10 @@ export const HEADERS_CREDENTIALS_FORMAT = "Format is Authorization: Bearer [token]"; export const ALLOWED_AUTHORIZATION_HEADER_CAPITALIZED = "Authorization"; -export const ALLOWED_AUTHORIZATION_HEADER_LOWERCASED = - ALLOWED_AUTHORIZATION_HEADER_CAPITALIZED.toLowerCase(); +export const ALLOWED_AUTHORIZATION_HEADER_LOWERCASED = "authorization"; export const INVALID_SCOPE_FIELD_TYPE = "Invalid scp field type"; export const INVALID_PEM_STRING = "Invalid PEM string"; + +export const INVALID_PUBLIC_KEY_FORMAT = "Invalid public key format (must be PEM, JWK, adhoc JWks or JWKs URI)" \ No newline at end of file diff --git a/src/vendors/jwks/jwks.ts b/src/vendors/jwks/jwks.ts index 8cac12e..5a5f1d9 100644 --- a/src/vendors/jwks/jwks.ts +++ b/src/vendors/jwks/jwks.ts @@ -1,11 +1,12 @@ import { createLocalJWKSet, importSPKI, - JWK, jwtVerify, - createRemoteJWKSet + createRemoteJWKSet, + JWK } from "jose"; import { extractAlgFromJwtHeader } from "../jwt"; +import {INVALID_PUBLIC_KEY_FORMAT} from "../../errors/messages" export interface IJwksClient { jwksUri?: string; // required for RS256 @@ -75,18 +76,19 @@ export interface ITokenExtractedWithPubKey { * * @param token token to verify * @param publicKey string is PEM, JWK is JSON Web Key - * @param opts - * @returns + * @param opts verifyRSA Token Credentials + * @returns decoded payload if token is valid */ export const verifyTokenWithPublicKey = async ( token: string, publicKey: string | JWK | null, - opts: IVerifyRSATokenCredentials = null + opts: IVerifyRSATokenCredentials = null, + adhocJwks: any[] = null ): Promise => { let JWKS = null; let decoded = null; - if (publicKey) { + if (publicKey || adhocJwks) { let jwk; if (typeof publicKey === "string") { const alg = extractAlgFromJwtHeader(token); @@ -97,16 +99,17 @@ export const verifyTokenWithPublicKey = async ( audience: opts?.requiredAudiences }); return decoded; - } else { + } else if (!!publicKey) { jwk = publicKey; } + JWKS = createLocalJWKSet({ - keys: [jwk] + keys: !!adhocJwks ? adhocJwks: [jwk] }); } else if (opts?.jwksUri) { JWKS = createRemoteJWKSet(new URL(opts?.jwksUri)) } else { - throw new Error("Invalid public key format (must be JWK or JWKs URI)"); + throw new Error(INVALID_PUBLIC_KEY_FORMAT); } try {