UNPKG

mcp-framework

Version:

Framework for building Model Context Protocol (MCP) servers in Typescript

52 lines (51 loc) 1.5 kB
import jwt from "jsonwebtoken"; import { DEFAULT_AUTH_ERROR } from "../types.js"; import { logger } from "../../core/Logger.js"; /** * JWT-based authentication provider */ export class JWTAuthProvider { config; constructor(config) { this.config = { algorithms: ["HS256"], headerName: "Authorization", requireBearer: true, ...config }; if (!this.config.secret) { throw new Error("JWT secret is required"); } } async authenticate(req) { const authHeader = req.headers[this.config.headerName.toLowerCase()]; if (!authHeader || typeof authHeader !== "string") { return false; } let token = authHeader; if (this.config.requireBearer) { if (!authHeader.startsWith("Bearer ")) { return false; } token = authHeader.split(" ")[1]; } try { const decoded = jwt.verify(token, this.config.secret, { algorithms: this.config.algorithms }); return { data: typeof decoded === "object" ? decoded : { sub: decoded } }; } catch (error) { logger.debug(`JWT verification failed: ${error.message}`); return false; } } getAuthError() { return { ...DEFAULT_AUTH_ERROR, message: "Invalid or expired JWT token" }; } }