### Install Kinde JWT Validator Source: https://github.com/kinde-oss/jwt-validator/blob/main/readme.md Install the library using npm, yarn, or pnpm. ```bash npm install @kinde/jwt-validator ``` ```bash yarn add @kinde/jwt-validator ``` ```bash pnpm install @kinde/jwt-validator ``` -------------------------------- ### Handle JWT Validation Errors Source: https://context7.com/kinde-oss/jwt-validator/llms.txt This example demonstrates comprehensive error handling for JWT validation. It covers scenarios like missing tokens, missing domain configurations, and various validation failures, returning structured error messages without throwing exceptions. ```typescript import { validateToken, type jwtValidationResponse } from "@kinde/jwt-validator"; async function authenticateRequest(authHeader: string | undefined) { // Handle missing token if (!authHeader) { const result = await validateToken({}); // { valid: false, message: "Token is required" } return { authenticated: false, error: result.message }; } // Handle missing domain configuration const result = await validateToken({ token: authHeader.replace("Bearer ", "") }); // { valid: false, message: "Domain is required" } // Full validation with proper parameters const validationResult = await validateToken({ token: authHeader.replace("Bearer ", ""), domain: process.env.KINDE_DOMAIN }); if (!validationResult.valid) { // Possible messages: // - "Invalid JWT format" (malformed token) // - "JWK not found" (kid doesn't match any key) // - "Invalid JWK RSA key" (key type mismatch) // - "Signature verification failed" (tampered token) return { authenticated: false, error: validationResult.message }; } return { authenticated: true }; } ``` -------------------------------- ### Validate JWT Token Source: https://github.com/kinde-oss/jwt-validator/blob/main/readme.md Import and use the `validateToken` function to validate a JWT token against your Kinde domain. Ensure you have the correct token and domain. ```javascript import { validateToken, type jwtValidationResponse } from "@kinde/jwt-validator"; const validationResult: jwtValidationResponse = await validateToken({ token: "eyJhbGc...", domain: "http://mybusiness.kinde.com" }); ``` -------------------------------- ### Validate Tokens with JWKS Caching Source: https://context7.com/kinde-oss/jwt-validator/llms.txt Demonstrates automatic JWKS caching and retry logic upon verification failure. ```typescript import { validateToken } from "@kinde/jwt-validator"; // First call: Fetches JWKS from https://mybusiness.kinde.com/.well-known/jwks.json const result1 = await validateToken({ token: "eyJhbGci...", domain: "https://mybusiness.kinde.com" }); // Second call: Uses cached JWKS (no network request) const result2 = await validateToken({ token: "eyJhbGci...", // Different token, same domain domain: "https://mybusiness.kinde.com" }); // If verification fails, library automatically: // 1. Clears cache for the domain // 2. Refetches JWKS from the server // 3. Retries verification with fresh keys // 4. Returns final result ``` -------------------------------- ### Integrate Express.js Middleware Source: https://context7.com/kinde-oss/jwt-validator/llms.txt Protects API routes by validating JWTs in the authorization header using middleware. ```typescript import express, { Request, Response, NextFunction } from "express"; import { validateToken, type jwtValidationResponse } from "@kinde/jwt-validator"; const app = express(); const KINDE_DOMAIN = "https://mybusiness.kinde.com"; // Authentication middleware async function authMiddleware(req: Request, res: Response, next: NextFunction) { const authHeader = req.headers.authorization; if (!authHeader?.startsWith("Bearer ")) { return res.status(401).json({ error: "Missing authorization header" }); } const token = authHeader.substring(7); const validation: jwtValidationResponse = await validateToken({ token, domain: KINDE_DOMAIN }); if (!validation.valid) { return res.status(401).json({ error: validation.message }); } next(); } // Protected route app.get("/api/protected", authMiddleware, (req: Request, res: Response) => { res.json({ message: "Access granted" }); }); app.listen(3000); ``` -------------------------------- ### validateToken Source: https://context7.com/kinde-oss/jwt-validator/llms.txt Validates a JWT token against a specified Kinde domain by verifying its signature using the domain's JWKS. ```APIDOC ## validateToken ### Description Validates a JWT token string against a Kinde domain. It fetches the JWKS from the domain's .well-known/jwks.json endpoint to verify the signature. ### Parameters #### Request Body - **token** (string) - Required - The JWT string to be validated. - **domain** (string) - Required - The Kinde domain URL (e.g., https://mybusiness.kinde.com). ### Request Example { "token": "eyJhbGciOiJSUzI1NiIs...", "domain": "https://mybusiness.kinde.com" } ### Response #### Success Response (200) - **valid** (boolean) - Indicates if the token signature is valid. - **message** (string) - A human-readable status or error description. #### Response Example { "valid": true, "message": "Token is valid" } ``` -------------------------------- ### Validate JWT Token Source: https://context7.com/kinde-oss/jwt-validator/llms.txt Use this function to validate a JWT token against your Kinde domain. Ensure you provide both the token and the domain URL. The function returns a structured response indicating validity and a message. ```typescript import { validateToken, type jwtValidationResponse } from "@kinde/jwt-validator"; // Basic token validation const result: jwtValidationResponse = await validateToken({ token: "eyJhbGciOiJSUzI1NiIsImtpZCI6IjRjOmZhOjllOmQ2OjQ3OjIzOmI3OjM5OmM3OjhmOjk3OjI4OjQ1OmExOjg0OjM1IiwidHlwIjoiSldUIn0.eyJkYXRhIjp7InVzZXIiOnsiZW1haWwiOiJ1c2VyQGV4YW1wbGUuY29tIiwiaWQiOiJrcF82NWIyOGQ3MWJiYTE0ZmEzODBkNTZkMmQ4ZDM1MDNkYSJ9fX0.signature", domain: "https://mybusiness.kinde.com" }); // Response when token is valid: // { valid: true, message: "Token is valid" } // Response when token has invalid signature: // { valid: false, message: "Signature verification failed" } // Response when token format is incorrect: // { valid: false, message: "Invalid JWT format" } ``` -------------------------------- ### Validate Webhook Signatures Source: https://context7.com/kinde-oss/jwt-validator/llms.txt Verifies webhook payloads from Kinde services using the JWKS endpoint. ```typescript import { validateToken } from "@kinde/jwt-validator"; interface KindeWebhookEvent { event_id: string; type: string; timestamp: string; data: { user: { id: string; email: string; first_name: string; last_name: string; }; }; } async function handleKindeWebhook(webhookToken: string): Promise { const validation = await validateToken({ token: webhookToken, domain: "https://mybusiness.kinde.com" }); if (!validation.valid) { console.error("Invalid webhook signature:", validation.message); return null; } // Decode the payload after validation const [, payloadBase64] = webhookToken.split("."); const payload = JSON.parse(atob(payloadBase64)); return payload as KindeWebhookEvent; } ``` -------------------------------- ### jwtValidationResponse Type Definition Source: https://context7.com/kinde-oss/jwt-validator/llms.txt This TypeScript type defines the structure of the response object returned by the `validateToken` function. It ensures a consistent format for handling validation results programmatically. ```typescript import { type jwtValidationResponse } from "@kinde/jwt-validator"; // Type definition type jwtValidationResponse = { valid: boolean; // true if token signature is valid message: string; // Human-readable status or error description }; // Usage in typed applications async function protectedEndpoint(token: string): Promise<{ data?: any; error?: string }> { const validation: jwtValidationResponse = await validateToken({ token, domain: "https://mybusiness.kinde.com" }); if (!validation.valid) { return { error: validation.message }; } return { data: { success: true } }; } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.