Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: useJWT() caches JWKS #3161

Open
wants to merge 16 commits into
base: main
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
26 changes: 17 additions & 9 deletions packages/plugins/jwt/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,8 @@ export function useJWT(options: JwtPluginOptions): Plugin {
const payloadByRequest = new WeakMap<Request, JwtPayload | string>();

let jwksClient: JwksClient;
const jwksCache: Map<string, string> = new Map();

if (options.jwksUri) {
jwksClient = new JwksClient({
cache: true,
Expand All @@ -82,8 +84,19 @@ export function useJWT(options: JwtPluginOptions): Plugin {
return {
async onRequestParse({ request, serverContext, url }) {
const token = await getToken({ request, serverContext, url });
if (token != null) {
const signingKey = options.signingKey ?? (await fetchKey(jwksClient, token));
if (token) {
const decodedToken = decode(token, { complete: true });
if (!decodedToken?.header?.kid) {
peterklingelhofer marked this conversation as resolved.
Show resolved Hide resolved
throw unauthorizedError(`Failed to decode authentication token. Missing key id.`);
}

let signingKey: string;
if (jwksCache.has(decodedToken.header.kid)) {
signingKey = jwksCache.get(decodedToken.header.kid)!;
} else {
signingKey = await fetchKey(jwksClient, decodedToken.header.kid);
jwksCache.set(decodedToken.header.kid, signingKey);
}
peterklingelhofer marked this conversation as resolved.
Show resolved Hide resolved

const verified = await verify(token, signingKey, options);

Expand Down Expand Up @@ -142,13 +155,8 @@ function verify(
});
}

async function fetchKey(jwksClient: JwksClient, token: string): Promise<string> {
const decodedToken = decode(token, { complete: true });
if (decodedToken?.header?.kid == null) {
throw unauthorizedError(`Failed to decode authentication token. Missing key id.`);
}

const secret = await jwksClient.getSigningKey(decodedToken.header.kid);
async function fetchKey(jwksClient: JwksClient, kid: string): Promise<string> {
const secret = await jwksClient.getSigningKey(kid);
const signingKey = secret?.getPublicKey();
if (!signingKey) {
throw unauthorizedError(`Failed to decode authentication token. Unknown key id.`);
Expand Down