Skip to content

Commit

Permalink
enable adhocJwks to verify tokens
Browse files Browse the repository at this point in the history
  • Loading branch information
dbrrt committed Nov 12, 2023
1 parent 849c23d commit fe6ee03
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 11 deletions.
5 changes: 3 additions & 2 deletions src/errors/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)"
21 changes: 12 additions & 9 deletions src/vendors/jwks/jwks.ts
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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<ITokenExtractedWithPubKey> => {
let JWKS = null;
let decoded = null;

if (publicKey) {
if (publicKey || adhocJwks) {
let jwk;
if (typeof publicKey === "string") {
const alg = extractAlgFromJwtHeader(token);
Expand All @@ -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 {
Expand Down

0 comments on commit fe6ee03

Please sign in to comment.