← Blog

Claude MCP skill JWT algorithm confusion and weak key validation — SA-SKL-AUTH13

JSON Web Tokens are the dominant authentication mechanism for MCP skill registry APIs — they're issued on login, validated on every request, and embedded in webhook payloads and CI integration tokens. When JWT validation is misconfigured, the consequences are total: an attacker who can forge a token claims any identity in the system. SA-SKL-AUTH13 covers four JWT implementation weaknesses specific to Node.js skill registry backends: algorithm confusion downgrade, short-secret brute-force, missing expiry validation in background workers, and kid-based SSRF via attacker-controlled key fetch.

By SkillAudit  |  12 Nov 2026
SA-SKL-AUTH13 findings at a glance
CRITICALAUTH13-001 — jsonwebtoken.verify(token, publicKey) without specifying algorithms: ['RS256']; attacker decodes the token header, changes alg to HS256, re-signs with the RSA public key as the HMAC secret (the public key is public — available from /.well-known/jwks.json); verify() accepts the forged token and the attacker impersonates any user
CRITICALAUTH13-002 — JWT HMAC secret shorter than 256 bits or derived from a predictable value (hostname, app name, secret123); attacker obtains a valid token (from a free-tier signup), runs hashcat with --hash-type 16500 offline; cracks the secret in minutes; signs arbitrary claims including {"role":"admin","orgId":"target-org-id"}
HIGHAUTH13-003 — JWT expiry (exp claim) not validated in the webhook delivery worker; worker uses a long-lived service account JWT stored in an env var; when an operator performs a credential rotation event and invalidates the old secret, the worker continues using the expired token for weeks until the env var is manually rotated — during that window the worker operates on a revoked credential
CRITICALAUTH13-004 — JWT kid (key ID) claim used to construct a URL from which the verification public key is fetched; attacker sets kid to https://169.254.169.254/latest/meta-data/; the server performs an HTTP GET to the metadata endpoint, uses the response as the public key material, and verifies the attacker's self-signed token against it — authentication bypass via SSRF

AUTH13-001 — Algorithm confusion: HS256 downgrade using RSA public key

The JWT algorithm confusion attack exploits a design flaw in early JWT library implementations: when verify(token, key) is called without specifying which algorithms are acceptable, the library reads the alg field from the token's own header to determine the verification algorithm. An attacker who possesses the RS256 public key (which is public — available from /.well-known/jwks.json on any standards-compliant JWKS endpoint) can craft a token with "alg":"HS256" in the header and sign it with HMAC-SHA256 using the RSA public key PEM as the HMAC secret bytes. The vulnerable verify(token, rsaPublicKey) call will then verify the HMAC signature using that same public key — and the token passes.

// VULNERABLE — AUTH13-001
// jsonwebtoken.verify() without algorithms constraint.
// Attacker obtains RSA public key from /.well-known/jwks.json.
// Crafts: header={"alg":"HS256","typ":"JWT"} + payload={"sub":"admin","role":"admin"}
// Signs with HMAC-SHA256 using the PEM-encoded RSA public key as secret.
// verify() accepts it because alg:HS256 matches HMAC(publicKey).

const jwt = require('jsonwebtoken');

function verifyToken(token) {
  // VULNERABLE: algorithms not specified — trusts the token's own alg header
  const payload = jwt.verify(token, process.env.JWT_PUBLIC_KEY);
  return payload;
}

// Attacker exploit:
// const attackerToken = jwt.sign(
//   { sub: 'admin', role: 'admin' },
//   publicKeyPem,  // RSA public key used as HMAC secret
//   { algorithm: 'HS256' }
// );
// verifyToken(attackerToken) → { sub: 'admin', role: 'admin' } ✓
// FIXED — AUTH13-001
// Fix: Always specify algorithms in verify() options.
// Using RS256: only RSA-SHA256 signatures accepted; HS256 downgrade impossible.
// Using HS256: specify 'HS256' explicitly — prevents 'none' algorithm attack.

const jwt = require('jsonwebtoken');

function verifyToken(token) {
  // FIX: algorithms array locks the acceptable algorithm — token header is ignored
  const payload = jwt.verify(token, process.env.JWT_PUBLIC_KEY, {
    algorithms: ['RS256'],  // FIX: explicit allowlist — HS256 downgrade rejected
    issuer: 'https://skillaudit.dev',
    audience: 'skillaudit-api',
  });
  return payload;
}

// Additional defense: validate that the public key is an RSA public key at startup
function validatePublicKey(key) {
  if (!key.includes('BEGIN PUBLIC KEY') && !key.includes('BEGIN RSA PUBLIC KEY')) {
    throw new Error('JWT_PUBLIC_KEY is not an RSA public key — refusing to start');
  }
}
validatePublicKey(process.env.JWT_PUBLIC_KEY);

The public key is public — that's the problem: RS256 is an asymmetric algorithm: the private key signs; the public key verifies. The public key is intentionally shared — it's served from /.well-known/jwks.json so that any service can verify tokens without having the private key. The algorithm confusion attack turns this into a liability: the attacker uses the public key (which they have) as an HMAC secret to forge tokens. Specifying algorithms: ['RS256'] is the fix because jsonwebtoken then validates the algorithm in the token header matches the algorithm in the options array before dispatching to the verification function — so a token with alg:HS256 is rejected before any key material is used.

AUTH13-002 — Short or predictable JWT HMAC secret

HMAC-based JWTs (HS256, HS384, HS512) derive their security entirely from the secrecy and length of the shared secret. The HMAC key space for HS256 is theoretically 256 bits, but nothing prevents an application from using a shorter or predictable value. JWT tokens are self-contained and can be obtained by anyone with a free-tier account — the token itself is the ciphertext that the attacker uses for offline brute-force. Tools like hashcat with --hash-type 16500 can test millions of HMAC-SHA256 keys per second against a captured JWT, cracking a 128-bit or dictionary-based secret in minutes to hours depending on GPU resources.

// VULNERABLE — AUTH13-002
// Short, predictable JWT secret. Attacker captures their own token (free signup),
// runs: hashcat -a 3 -m 16500 token.jwt ?d?d?d?d?d?d?d?d
// Or uses rockyou.txt: hashcat -a 0 -m 16500 token.jwt rockyou.txt
// Cracks the secret "skillaudit2026" in seconds.
// Now signs: jwt.sign({sub:"admin",role:"admin"}, "skillaudit2026", {algorithm:"HS256"})

const jwt = require('jsonwebtoken');

// VULNERABLE: short, predictable secret
const JWT_SECRET = process.env.JWT_SECRET || 'skillaudit2026';

function signToken(payload) {
  return jwt.sign(payload, JWT_SECRET, { algorithm: 'HS256', expiresIn: '7d' });
}

function verifyToken(token) {
  return jwt.verify(token, JWT_SECRET, { algorithms: ['HS256'] });
}
// FIXED — AUTH13-002
// Fix 1: Require a 256-bit (32-byte) random secret; throw at startup if too short.
// Fix 2: Generate the secret with: node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
// Fix 3: Rotate the secret periodically and validate exp on all tokens (see AUTH13-003).

const jwt = require('jsonwebtoken');
const crypto = require('crypto');

function validateJwtSecret(secret) {
  if (!secret) throw new Error('JWT_SECRET is not set — refusing to start');
  const buf = Buffer.from(secret, 'utf8');
  // FIX 1: Require at least 256 bits (32 bytes)
  if (buf.length < 32) {
    throw new Error(`JWT_SECRET is too short (${buf.length} bytes); minimum 32 bytes required`);
  }
}

validateJwtSecret(process.env.JWT_SECRET);
const JWT_SECRET = process.env.JWT_SECRET;

// FIX 2: Secure token generation — always check bit strength at startup
function signToken(payload) {
  return jwt.sign(payload, JWT_SECRET, {
    algorithm: 'HS256',
    expiresIn: '1h',      // FIX: shorter expiry reduces brute-force window
    issuer: 'https://skillaudit.dev',
    audience: 'skillaudit-api',
  });
}

function verifyToken(token) {
  return jwt.verify(token, JWT_SECRET, {
    algorithms: ['HS256'],
    issuer: 'https://skillaudit.dev',
    audience: 'skillaudit-api',
  });
}

AUTH13-003 — JWT expiry not validated in webhook delivery worker

Background workers that deliver webhook events to developer-registered endpoints authenticate outbound requests using a service account JWT stored in an environment variable. This JWT was issued once during provisioning and has a far-future exp claim — or no exp claim at all. When an operator performs a JWT secret rotation (a standard security operation), they update the secret but forget to regenerate the service account token stored in the worker's env var. The worker continues using the old token, which is now signed with the revoked secret. Meanwhile, the developer's webhook receiver that validates inbound JWTs from the registry now rejects the worker's requests — or accepts them if it uses a permissive verification path. Neither failure mode is immediately visible.

// VULNERABLE — AUTH13-003
// Webhook worker uses long-lived service account JWT from env var.
// JWT has no exp claim and was signed with the old secret.
// After secret rotation, the worker's token is invalid — but exp is never re-checked.

class WebhookWorker {
  constructor() {
    // VULNERABLE: JWT loaded once at startup; never re-validated or refreshed
    this.serviceToken = process.env.WEBHOOK_SERVICE_JWT;
  }

  async deliverWebhook(endpoint, payload) {
    const res = await fetch(endpoint.url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${this.serviceToken}`, // VULNERABLE: stale token
        'X-SkillAudit-Signature': hmacSignature(payload),
      },
      body: JSON.stringify(payload),
    });
    return res.status;
  }
}
// FIXED — AUTH13-003
// Fix 1: Validate the exp claim on the service token at startup and on each use.
// Fix 2: Implement automatic token refresh: re-fetch service account token on 401.
// Fix 3: Issue service account JWTs with short expiry (1 hour) and a refresh endpoint.

const jwt = require('jsonwebtoken');

class WebhookWorker {
  constructor() {
    this.serviceToken = null;
    this.tokenExp = 0;
  }

  // FIX 1: Check exp before each use; refresh if expired or expiring within 5 minutes
  async getServiceToken() {
    const now = Math.floor(Date.now() / 1000);
    if (this.serviceToken && this.tokenExp > now + 300) {
      return this.serviceToken;
    }
    // FIX 3: Fetch fresh short-lived token from internal auth endpoint
    return this._refreshServiceToken();
  }

  async _refreshServiceToken() {
    const res = await fetch('http://auth-service/internal/service-tokens', {
      method: 'POST',
      headers: { 'Authorization': `Bearer ${process.env.SERVICE_ACCOUNT_SECRET}` },
    });
    if (!res.ok) throw new Error('Failed to refresh service account token');
    const { token } = await res.json();

    // FIX 2: Validate the new token before caching it
    const decoded = jwt.decode(token);
    if (!decoded?.exp) throw new Error('Service token has no exp claim — refusing to use');
    this.serviceToken = token;
    this.tokenExp = decoded.exp;
    return token;
  }

  async deliverWebhook(endpoint, payload) {
    const token = await this.getServiceToken();
    const res = await fetch(endpoint.url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`,
        'X-SkillAudit-Signature': hmacSignature(payload),
      },
      body: JSON.stringify(payload),
    });

    // FIX 2: On 401, invalidate cached token and retry once with fresh token
    if (res.status === 401) {
      this.serviceToken = null;
      const freshToken = await this._refreshServiceToken();
      return fetch(endpoint.url, {
        method: 'POST',
        headers: { 'Authorization': `Bearer ${freshToken}` },
        body: JSON.stringify(payload),
      });
    }
    return res;
  }
}

AUTH13-004 — JWT kid claim SSRF via attacker-controlled public key fetch

The JWT kid (key ID) header claim is intended to help the verifier select the correct key when multiple keys are in rotation. Some implementations use the kid value to construct a URL from which to fetch the public key — a pattern borrowed from OIDC JWKS discovery. When the kid-to-URL mapping is not strictly validated against a pre-loaded key registry, an attacker can set kid to any URL — including https://169.254.169.254/latest/meta-data/iam/security-credentials/role. The server fetches the attacker's URL, uses the response (which is not a valid key) as key material, and the JWT verification either fails or — worse — accepts a token signed with key material the attacker chose.

// VULNERABLE — AUTH13-004
// JWT kid used to construct URL for public key fetch.
// Attacker crafts token header: {"alg":"RS256","kid":"https://169.254.169.254/latest/meta-data/"}
// Server fetches that URL, uses the response as the public key — verification fails or
// attacker constructs a carefully-crafted response that "passes" a permissive verify() call.

async function verifyToken(token) {
  const decoded = jwt.decode(token, { complete: true });
  const { kid } = decoded.header;

  // VULNERABLE: kid used as URL to fetch public key — SSRF
  const keyRes = await fetch(kid);  // fetches internal metadata endpoint!
  const publicKey = await keyRes.text();

  return jwt.verify(token, publicKey, { algorithms: ['RS256'] });
}
// FIXED — AUTH13-004
// Fix 1: Pre-load the key registry at startup — never fetch keys at verification time.
// Fix 2: Validate kid against a strict allowlist of known key IDs.
// Fix 3: If JWKS endpoint fetching is required, fetch only from a hardcoded trusted URL —
//        never from a URL in the token itself.

const jwt = require('jsonwebtoken');

// FIX 1: Pre-load keys at startup from a trusted, hardcoded JWKS endpoint
const KEY_REGISTRY = new Map(); // kid → public key PEM

async function loadKeyRegistry() {
  // FIX 3: Hardcoded JWKS URL — never from token header
  const res = await fetch('https://skillaudit.dev/.well-known/jwks.json');
  const { keys } = await res.json();
  for (const key of keys) {
    // Convert JWK to PEM using a library like node-jose or jose
    KEY_REGISTRY.set(key.kid, jwkToPem(key));
  }
}

// Called at startup; refreshed on a schedule (not on each request)
await loadKeyRegistry();

function verifyToken(token) {
  const decoded = jwt.decode(token, { complete: true });
  if (!decoded) throw new Error('Invalid token format');

  const { kid } = decoded.header;

  // FIX 2: kid must be in the pre-loaded registry — never fetch from kid URL
  const publicKey = KEY_REGISTRY.get(kid);
  if (!publicKey) {
    throw new Error(`Unknown kid '${kid}' — token rejected`);
  }

  return jwt.verify(token, publicKey, {
    algorithms: ['RS256'],
    issuer: 'https://skillaudit.dev',
    audience: 'skillaudit-api',
  });
}

JWKS endpoint vs. kid-based fetch: The correct pattern for key discovery is OIDC JWKS: the server exposes a /.well-known/jwks.json endpoint at a hardcoded, known URL; clients (or other servers) fetch this once at startup and cache all keys. The kid claim is then used only as a local lookup in that cached registry. The vulnerable pattern — where kid is used as a URL to fetch the key — conflates the key ID (a lookup key) with a key source (a URL), making the entire key management system SSRF-vulnerable to anyone who can present a token.

Summary — SA-SKL-AUTH13 at a glance

PatternRoot causeFixSeverity
AUTH13-001verify() without algorithms — trusts token's own alg headeralgorithms: ['RS256'] in verify optionsCRITICAL
AUTH13-002HMAC secret too short or predictable — offline brute-forceRequire 256-bit random secret; validate at startupCRITICAL
AUTH13-003exp claim not validated in background worker; stale token survives rotationCheck exp before each use; auto-refresh on 401HIGH
AUTH13-004kid claim used as URL to fetch public key — SSRFPre-load key registry at startup; kid is a lookup key, not a URLCRITICAL

SkillAudit's JWT scanner checks all four SA-SKL-AUTH13 patterns: it inspects jsonwebtoken.verify() calls for missing algorithms constraints, checks JWT secret strength (entropy bits), scans worker code for exp validation, and detects kid-to-URL fetch patterns that enable SSRF. See also SA-SKL-AUTH12 (session management vulnerabilities) and SA-SKL-AUTH11 (OAuth2 and PKCE vulnerabilities).