← Blog

Claude skill JWT kid header injection and JWK key confusion — SA-SKL-JWT4

The kid (Key ID) header parameter in a JWT is designed to help the verifier select the correct signing key when multiple keys are in rotation. SA-SKL-JWT4 covers four patterns where this key-selection mechanism becomes an authentication bypass: injecting SQL into an unsanitised kid value to select a known key; using the kid to traverse the filesystem and load an attacker-readable file as the signing key; exploiting libraries that honour a jwks_uri claim in the token header to fetch an attacker-controlled key set; and storing refresh tokens without absolute expiry so they remain valid indefinitely.

By SkillAudit  |  7 Nov 2026

The kid header: flexible by design, dangerous by default

JWTs are signed, not encrypted, and the header is base64-decoded without verification before the signature is checked. This means every field in the JWT header — including kid — arrives at the server as raw attacker-controlled input before any trust has been established. The JWT specification defines kid as an application-defined string with no constraints on format or length, leaving every implementation to sanitise it appropriately. In practice, most JWT middleware documentation shows the kid value being passed directly to database queries or filesystem reads in example code, normalising the vulnerable pattern.

MCP skills that implement custom JWT verification — common when skills need to issue their own tokens for session management or when they verify tokens issued by a custom identity provider — are especially at risk. The jsonwebtoken library's callback-based key retrieval pattern and the jwks-rsa JWKS fetching library both require the developer to explicitly validate the kid value before using it. SkillAudit's SA-SKL-JWT4 scanner checks for all four bypass patterns in a single scan.

SA-SKL-JWT4 findings at a glance
CRITICALJWT4-001 — kid header SQL injection: SELECT key FROM keys WHERE kid = '${header.kid}' returns attacker-known key
CRITICALJWT4-002 — kid header path traversal: fs.readFileSync(path.join('/keys', header.kid)) reads .env as signing key
CRITICALJWT4-003 — jwks_uri in token header fetches attacker-controlled JWK Set; signed with known private key
HIGHJWT4-004 — Refresh token stored without absolute expiry; 2-year-old token replays successfully

JWT4-001 — kid header SQL injection selects attacker-known signing key

When a JWT verification handler uses the kid header to look up the signing key in a database, it must use parameterised queries. String interpolation of the kid value into a raw SQL query creates a classic SQL injection — but with a twist: the attacker controls which key is returned, not just whether the query succeeds. By injecting ' OR '1'='1'--, the attacker modifies the query to return the first row in the keys table regardless of the actual kid. If the attacker has previously stored a key they know (e.g. by registering a skill that creates a key entry in the shared table), or if the first row is a test key with known value, they can forge a JWT signed with that key.

The fix is a parameterised query and a format validation on the kid value before it ever reaches the database. Keys table entries should use UUID primary keys; the kid header should be validated against a UUID regex before the lookup. If the kid does not match the expected format, reject the token immediately with a 401 — do not fall through to a permissive lookup.

// VULNERABLE — kid header interpolated into SQL query
import jwt from 'jsonwebtoken';
import { pool } from './db.js';

async function verifyToken(token) {
  // Decode header WITHOUT verification — header is attacker-controlled
  const decoded = jwt.decode(token, { complete: true });
  const kid = decoded?.header?.kid;

  // VULNERABLE: kid is raw user input, interpolated into SQL
  // Attacker sets kid = "' OR '1'='1'--"
  // Resulting query: SELECT key FROM keys WHERE kid = '' OR '1'='1'--'
  // Returns the first row — an attacker-known or attacker-inserted key
  const result = await pool.query(
    `SELECT key FROM keys WHERE kid = '${kid}'`
  );

  if (!result.rows[0]) throw new Error('Key not found');
  const signingKey = result.rows[0].key;

  return jwt.verify(token, signingKey);
}
// FIXED — parameterised query + UUID format validation on kid
import jwt from 'jsonwebtoken';
import Ajv from 'ajv';
import addFormats from 'ajv-formats';
import { pool } from './db.js';

const ajv = new Ajv();
addFormats(ajv);

const kidSchema = { type: 'string', format: 'uuid' };
const validateKid = ajv.compile(kidSchema);

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

  // Validate kid format before any database interaction
  if (!kid || !validateKid(kid)) {
    throw new Error('Invalid or missing kid header');
  }

  // Parameterised query — kid value is passed as a bind parameter, never interpolated
  const result = await pool.query(
    'SELECT key FROM keys WHERE kid = $1 AND active = true',
    [kid]  // $1 bound to the sanitised kid string
  );

  if (!result.rows[0]) throw new Error('Signing key not found');

  return jwt.verify(token, result.rows[0].key, {
    algorithms: ['RS256'],  // allowlist — never 'none' or symmetric + asymmetric mix
  });
}

JWT4-002 — kid header path traversal reads arbitrary file as signing key

An alternative to database key storage is loading signing keys from the filesystem — a PEM file per key, named by kid. When the server constructs the file path from the kid header value using path.join(keysDir, header.kid), a kid value of ../../.env resolves to the application's environment file. The contents of .env — which includes database passwords, API keys, and secret tokens — are then loaded as the JWT signing key. The attacker constructs a JWT signed with the known HMAC-SHA256 signature of .env contents (which they can enumerate from the response body or server logs if the application echoes parts of the key) and submits it for authentication.

The fix is a path confinement check and an allowlist of valid key identifiers. After constructing the candidate path, assert that the resolved path starts with the keys directory using path.resolve() and startsWith(keysDir + path.sep). Additionally, maintain an in-memory allowlist (or a database allowlist) of valid kid values and reject any kid not in the set. Never construct a filesystem path from a JWT header field.

// VULNERABLE — kid used to construct filesystem path without bounds check
import jwt from 'jsonwebtoken';
import { readFileSync } from 'fs';
import { join } from 'path';

const KEYS_DIR = '/app/keys';

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

  // VULNERABLE: kid = "../../.env"
  // path.join('/app/keys', '../../.env') resolves to /app/.env
  // readFileSync loads the .env file as the JWT signing key
  // Attacker signs a token with HMAC(contents of .env) — authentication bypassed
  const keyPath = join(KEYS_DIR, kid);
  const signingKey = readFileSync(keyPath, 'utf8');

  return jwt.verify(token, signingKey);
}
// FIXED — path confinement + explicit kid allowlist
import jwt from 'jsonwebtoken';
import { readFileSync } from 'fs';
import { join, resolve, sep } from 'path';

const KEYS_DIR = resolve('/app/keys');

// Allowlist of valid kid values loaded at startup from the database
// Never constructed from request data at runtime
const VALID_KIDS = new Set(['key-2024-01', 'key-2025-06', 'key-2026-01']);

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

  // Step 1: check allowlist — only pre-registered key IDs are accepted
  if (!kid || !VALID_KIDS.has(kid)) {
    throw new Error('Unknown or invalid kid');
  }

  // Step 2: construct path and verify confinement even though kid is already allowlisted
  // Double defence: allowlist prevents unknown kids; path check prevents allowlist bypass
  const keyPath = resolve(KEYS_DIR, kid + '.pem');
  if (!keyPath.startsWith(KEYS_DIR + sep)) {
    throw new Error('Key path traversal detected');
  }

  const signingKey = readFileSync(keyPath, 'utf8');
  return jwt.verify(token, signingKey, { algorithms: ['RS256'] });
}

JWT4-003 — jwks_uri in token header fetches attacker-controlled JWK Set

The JSON Web Key Set (JWKS) standard allows servers to publish their public signing keys at a well-known URI (e.g. https://auth.example.com/.well-known/jwks.json). Some JWT libraries and identity middleware support a jwks_uri claim in the JWT header itself, allowing the token to specify where the verifier should fetch the signing key. This is an SSRF-class vulnerability: the attacker sets jwks_uri to a server they control, publishes a JWK Set containing their own public key, signs a JWT with their private key, and the vulnerable verifier fetches and trusts the attacker's public key. The result is a complete authentication bypass — the attacker can forge tokens for any user.

The fix is to hardcode the JWKS URI in the server configuration and never read it from the token. The jwks-rsa library's JwksClient takes a jwksUri in its constructor options — set it once at application startup from an environment variable or config file, never from the incoming token. Additionally, enable caching (cache: true, cacheMaxEntries: 10, cacheMaxAge: 86400) to avoid per-request JWKS fetches and to limit the blast radius of a compromised key endpoint.

// VULNERABLE — library reads jwks_uri from token header and fetches it
import jwt from 'jsonwebtoken';
import jwksClient from 'jwks-rsa';

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

  // VULNERABLE: library configured to follow jwks_uri from the token header
  // Attacker sets header.jwks_uri = 'https://attacker.com/evil-jwks.json'
  // Library fetches attacker's JWKS, gets attacker's public key, verifies signature
  // Authentication is bypassed — attacker can forge tokens for any sub/email
  const client = jwksClient({
    jwksUri: header.jwks_uri,  // ← reading URI from the token being verified
  });

  const key = await client.getSigningKey(header.kid);
  return jwt.verify(token, key.getPublicKey());
}
// FIXED — hardcode JWKS URI in server config; never read from token header
import jwt from 'jsonwebtoken';
import jwksClient from 'jwks-rsa';
import { promisify } from 'util';

// JWKS URI set at startup from environment or config — NEVER from token headers
const client = jwksClient({
  jwksUri: process.env.JWKS_URI,  // e.g. https://auth.skillaudit.dev/.well-known/jwks.json
  cache: true,
  cacheMaxEntries: 10,
  cacheMaxAge: 86400 * 1000,     // 24 hours in ms
  rateLimit: true,
  jwksRequestsPerMinute: 10,
});

const getKey = (header, callback) => {
  client.getSigningKey(header.kid, (err, key) => {
    if (err) return callback(err);
    callback(null, key.getPublicKey());
  });
};

const verifyAsync = promisify(jwt.verify.bind(jwt));

async function verifyToken(token) {
  // jwt.verify calls getKey(header, callback) — header is from the token
  // but getKey only uses header.kid to select a key from the hardcoded JWKS URI
  // header.jwks_uri is completely ignored — library never reads it
  return verifyAsync(token, getKey, {
    algorithms: ['RS256'],
    issuer: process.env.JWT_ISSUER,
    audience: process.env.JWT_AUDIENCE,
  });
}

JWT4-004 — Refresh token stored without absolute expiry enables indefinite replay

Short-lived access tokens (exp in 15 minutes) are a common JWT security practice. The corresponding refresh token is intended to have a longer but still bounded lifetime, stored securely server-side and invalidated on use. When a refresh token is stored in the database without an absolute maximum lifetime — or when the exp claim on the refresh token is set far in the future and never enforced server-side — an attacker who obtains an old refresh token (from a leaked database backup, a compromised log file, or a client-side storage breach) can replay it months or years later to obtain a fresh access token.

The fix has three components: store the issuedAt timestamp for each refresh token in the database; enforce an absolute maximum lifetime (e.g. 90 days) server-side by comparing issuedAt to the current time; and rotate the refresh token on each use — issue a new refresh token and invalidate the old one atomically in a database transaction (this is called refresh token rotation). Single-use refresh tokens limit the window of a leaked token to the next refresh cycle.

// VULNERABLE — refresh token stored without expiry check; replays indefinitely
import { pool } from './db.js';
import jwt from 'jsonwebtoken';

async function refreshAccessToken(refreshToken) {
  // Look up refresh token in database
  const result = await pool.query(
    'SELECT user_id, created_at FROM refresh_tokens WHERE token = $1',
    [refreshToken]
  );

  if (!result.rows[0]) throw new Error('Invalid refresh token');

  const { user_id } = result.rows[0];
  // VULNERABLE: no check on created_at — token from 2 years ago is accepted
  // No rotation — same token works forever until manually revoked
  // No expiry column — no way to bulk-expire old tokens

  return jwt.sign(
    { sub: user_id, type: 'access' },
    process.env.JWT_SECRET,
    { expiresIn: '15m' }
  );
}
// FIXED — absolute expiry + rotation + single-use enforcement
import { pool } from './db.js';
import jwt from 'jsonwebtoken';
import { randomBytes } from 'crypto';

const REFRESH_TOKEN_MAX_AGE_MS = 90 * 24 * 60 * 60 * 1000; // 90 days absolute maximum

async function refreshAccessToken(refreshToken) {
  const client = await pool.connect();
  try {
    await client.query('BEGIN');

    // Lock the row for update to prevent concurrent replay
    const result = await client.query(
      `SELECT user_id, issued_at, used_at
       FROM refresh_tokens
       WHERE token = $1
       FOR UPDATE`,
      [refreshToken]
    );

    if (!result.rows[0]) {
      await client.query('ROLLBACK');
      throw new Error('Invalid refresh token');
    }

    const { user_id, issued_at, used_at } = result.rows[0];

    // Single-use check — token already consumed = possible replay attack
    if (used_at) {
      // Rotate detected: revoke ALL tokens for this user (may indicate compromise)
      await client.query('DELETE FROM refresh_tokens WHERE user_id = $1', [user_id]);
      await client.query('COMMIT');
      throw new Error('Refresh token already used — all sessions revoked');
    }

    // Absolute expiry check — reject tokens older than 90 days regardless of DB state
    const ageMs = Date.now() - new Date(issued_at).getTime();
    if (ageMs > REFRESH_TOKEN_MAX_AGE_MS) {
      await client.query('DELETE FROM refresh_tokens WHERE token = $1', [refreshToken]);
      await client.query('COMMIT');
      throw new Error('Refresh token expired');
    }

    // Mark old token as used (tombstone — not deleted, to detect replay)
    await client.query(
      'UPDATE refresh_tokens SET used_at = NOW() WHERE token = $1',
      [refreshToken]
    );

    // Issue new refresh token (rotation)
    const newRefreshToken = randomBytes(48).toString('base64url');
    await client.query(
      'INSERT INTO refresh_tokens (user_id, token, issued_at) VALUES ($1, $2, NOW())',
      [user_id, newRefreshToken]
    );

    await client.query('COMMIT');

    const accessToken = jwt.sign(
      { sub: user_id, type: 'access' },
      process.env.JWT_SECRET,
      { expiresIn: '15m' }
    );

    return { accessToken, refreshToken: newRefreshToken };
  } catch (err) {
    await client.query('ROLLBACK');
    throw err;
  } finally {
    client.release();
  }
}

Summary table — SA-SKL-JWT4 patterns

IDSeverityRoot causeFix
JWT4-001CRITICALkid interpolated into SQL — attacker selects known keyParameterised query + UUID format validation on kid
JWT4-002CRITICALkid used in filesystem path — ../../.env loaded as signing keypath.resolve() + startsWith() + kid allowlist
JWT4-003CRITICALjwks_uri read from token header — attacker serves own JWK SetHardcode JWKS URI in server config; never read from token
JWT4-004HIGHNo absolute refresh token expiry — indefinite replay after DB breach90-day absolute expiry + rotation + single-use tombstone

SkillAudit scans for all four SA-SKL-JWT4 patterns automatically. Run a free scan at skillaudit.dev or see related patterns: SA-SKL-JWT3, SA-SKL-SSRF8.