how do I validate a jwt using a jwks in pages?

How can I implement in cloudflare’s runtime a jwt validatation using information from the jwks endpoint ? Any tips?
2 Replies
zegevlier
zegevlier12mo ago
Where are you getting stuck?
Ricardo Viteri
Ricardo Viteri12mo ago
I was stuck with the implementation, but I solved it like this:
import { AUTH_SERVER_URL } from "$env/static/private";

import jwt from "@tsndr/cloudflare-worker-jwt";

interface JwksResponse {
keys: Jwk[];
}

interface Jwk {
alg: string;
e: string;
kid: string;
kty: string;
n: string;
use: string;
x5c: string[];
x5t: string;
"x5t#S256": string;
}

async function findKey(jwks: JwksResponse, kid: string) {
const keys = jwks.keys;
const key = keys.find((k) => k.kid === kid);
return key;
}

export async function isJwtValid(token: string): Promise<boolean> {
if (!token) return false;

try {
const decodedToken = jwt.decode(token);
const kid = decodedToken.header.kid;
const jwksUrl = `${AUTH_SERVER_URL}/.well-known/jwks.json`;
const jwksResponse = await fetch(jwksUrl);
const jwks: JwksResponse = await jwksResponse.json();
const key: Jwk | undefined = await findKey(jwks, kid);
if (!key) {
throw new Error("Public key not found in jwks.json");
}

const algorithm = key.alg;
const isValid = await jwt.verify(token, <JsonWebKey>key, {
algorithm: algorithm
});

console.log("JWT is valid:", isValid);

return isValid;
} catch (error) {
console.error("Failed to validate JWT:", error);
return false;
}
}
import { AUTH_SERVER_URL } from "$env/static/private";

import jwt from "@tsndr/cloudflare-worker-jwt";

interface JwksResponse {
keys: Jwk[];
}

interface Jwk {
alg: string;
e: string;
kid: string;
kty: string;
n: string;
use: string;
x5c: string[];
x5t: string;
"x5t#S256": string;
}

async function findKey(jwks: JwksResponse, kid: string) {
const keys = jwks.keys;
const key = keys.find((k) => k.kid === kid);
return key;
}

export async function isJwtValid(token: string): Promise<boolean> {
if (!token) return false;

try {
const decodedToken = jwt.decode(token);
const kid = decodedToken.header.kid;
const jwksUrl = `${AUTH_SERVER_URL}/.well-known/jwks.json`;
const jwksResponse = await fetch(jwksUrl);
const jwks: JwksResponse = await jwksResponse.json();
const key: Jwk | undefined = await findKey(jwks, kid);
if (!key) {
throw new Error("Public key not found in jwks.json");
}

const algorithm = key.alg;
const isValid = await jwt.verify(token, <JsonWebKey>key, {
algorithm: algorithm
});

console.log("JWT is valid:", isValid);

return isValid;
} catch (error) {
console.error("Failed to validate JWT:", error);
return false;
}
}