← Blog

Claude MCP skill JWT claim confusion — access & refresh token security — SA-SKL-AUTH4

JWT authentication in MCP skills breaks down in four distinct ways that are each invisible at the library level: signing access tokens and refresh tokens with the same HMAC secret so a long-lived refresh token can be substituted for a short-lived access token; omitting JTI tracking so a revoked token remains usable until expiry; widening clock skew tolerance to hours to paper over NTP drift rather than fixing the drift; and skipping audience validation so a token minted for the staging environment is happily accepted by the production API. Each pattern produces an authentication bypass that bypasses scope enforcement, session revocation, or environment isolation.

By SkillAudit  |  8 Nov 2026

JWT token design in MCP skill authentication flows

An MCP skill typically issues two token types during authentication: a short-lived access token (5–15 minutes) that grants API access with specific scope claims, and a long-lived refresh token (hours to days) used only to obtain a new access token from the token endpoint. The security model depends entirely on these token types being cryptographically distinct — either by using separate signing secrets or by embedding a typ claim that the verifying middleware checks before granting access. When the tokens are indistinguishable to the verifier, an attacker who obtains a refresh token (which is often stored in less-protected storage than access tokens, or which appears in server logs at the token endpoint) can replay it against the resource API and bypass the access token's scope constraints.

Beyond token type confusion, two operational failures compound the problem: not tracking JWT IDs (the jti claim) means logout and password reset have no effect until the token expires naturally; and not validating the aud (audience) claim means tokens issued during development or for a different service tenant can be replayed against production. These four patterns together define the SA-SKL-AUTH4 rule set that SkillAudit detects during static and dynamic analysis of MCP skill repositories.

SA-SKL-AUTH4 findings at a glance
CRITICALAUTH4-001 — Access token and refresh token signed with same HMAC secret and no typ or use claim; attacker presents 30-day refresh token as access token; scope restrictions on access tokens not enforced
HIGHAUTH4-002 — JTI claim not stored in Redis and checked on each request; revoked tokens remain valid until natural expiry; logout and password reset have no immediate effect
MEDIUMAUTH4-003 — JWT expiry validated with 1-hour clock skew leeway added to work around NTP drift; short-lived access tokens (15-minute TTL) effectively granted 1h15m validity, defeating expiry enforcement
HIGHAUTH4-004 — JWT audience (aud) claim not validated; token issued for skillaudit-staging accepted on production API server because jwt.verify() called without audience option

AUTH4-001 — Shared HMAC secret causes access/refresh token type confusion

When both token types are signed with the same HMAC secret and neither carries a typ claim (or the middleware does not check the typ claim), the verifier cannot distinguish them. A refresh token issued with a 30-day expiry, presented to the resource API as an access token, will pass signature and expiry verification. The scope claims on access tokens — which may restrict a token to read-only operations or to a specific resource namespace — are absent from refresh tokens, so the attacker effectively holds an unrestricted, long-lived credential.

The fix is either separate signing secrets for each token type (simple, deterministic, no claim validation required) or a typ claim that the access-control middleware validates before proceeding. The typ approach is more flexible when secret rotation is managed centrally, but requires that every verification call site explicitly checks the claim. Using separate secrets is safer by default because even a verification call site that forgets to check typ will reject the wrong token type due to signature mismatch.

// VULNERABLE — both token types signed with the same secret, no typ claim
import jwt from 'jsonwebtoken';

const SECRET = process.env.JWT_SECRET; // single secret for all tokens

function issueAccessToken(userId, scopes) {
  // VULNERABLE: no typ claim; same secret as refresh token
  return jwt.sign({ sub: userId, scopes }, SECRET, { expiresIn: '15m' });
}

function issueRefreshToken(userId) {
  // VULNERABLE: same SECRET; refresh token passes access token verification
  return jwt.sign({ sub: userId }, SECRET, { expiresIn: '30d' });
}

// Middleware — VULNERABLE: does not check typ; refresh token accepted here
function requireAuth(req, res, next) {
  const token = req.headers.authorization?.split(' ')[1];
  try {
    const payload = jwt.verify(token, SECRET); // accepts refresh tokens too
    req.user = payload;
    next();
  } catch (err) {
    res.status(401).json({ error: 'Unauthorized' });
  }
}
// FIXED — separate secrets per token type AND typ claim validation
import jwt from 'jsonwebtoken';

const ACCESS_SECRET  = process.env.JWT_ACCESS_SECRET;   // separate secret
const REFRESH_SECRET = process.env.JWT_REFRESH_SECRET;  // separate secret

function issueAccessToken(userId, scopes) {
  return jwt.sign(
    { sub: userId, scopes, typ: 'access' },
    ACCESS_SECRET,
    { expiresIn: '15m', algorithm: 'HS256' }
  );
}

function issueRefreshToken(userId) {
  return jwt.sign(
    { sub: userId, typ: 'refresh' },
    REFRESH_SECRET,
    { expiresIn: '30d', algorithm: 'HS256' }
  );
}

// Middleware — rejects refresh tokens at two layers: wrong secret + wrong typ
function requireAuth(req, res, next) {
  const token = req.headers.authorization?.split(' ')[1];
  if (!token) return res.status(401).json({ error: 'Unauthorized' });
  try {
    const payload = jwt.verify(token, ACCESS_SECRET, { algorithms: ['HS256'] });
    // Double-check typ even if secret somehow matched
    if (payload.typ !== 'access') {
      return res.status(401).json({ error: 'Invalid token type' });
    }
    req.user = payload;
    next();
  } catch (err) {
    res.status(401).json({ error: 'Unauthorized' });
  }
}

// Token endpoint — only accepts refresh tokens signed with REFRESH_SECRET
app.post('/auth/token', async (req, res) => {
  const { refreshToken } = req.body;
  try {
    const payload = jwt.verify(refreshToken, REFRESH_SECRET, { algorithms: ['HS256'] });
    if (payload.typ !== 'refresh') return res.status(401).json({ error: 'Invalid token type' });
    const accessToken = issueAccessToken(payload.sub, DEFAULT_SCOPES);
    res.json({ accessToken });
  } catch (err) {
    res.status(401).json({ error: 'Invalid refresh token' });
  }
});

AUTH4-002 — Missing JTI storage means revoked tokens remain valid

The jti (JWT ID) claim is a unique identifier for a specific token instance. Its security value is conditional: it only enables revocation if the server stores each issued JTI and checks incoming tokens against that store before proceeding. Without that check, jti is decorative. When a user logs out or changes their password, the server typically deletes the session record and returns a 200 response — but if JTI checking is absent, any access token the attacker extracted before the logout event continues to be valid for the remainder of its TTL. For a 15-minute access token this is a narrow window, but for implementations that widened the TTL to reduce token refresh overhead, the exposure can be measured in hours.

The correct implementation stores the JTI in Redis with a TTL equal to the token's expiry time on issue, and checks for the presence of the JTI key on every authenticated request. On revocation (logout, password reset, forced session termination), the JTI key is deleted from Redis. Redis is appropriate here because the check is on the hot path and must be O(1); a database query adds unacceptable latency at the authentication middleware layer.

// VULNERABLE — jti claim present but never stored or checked; logout is cosmetic
import jwt from 'jsonwebtoken';
import { v4 as uuidv4 } from 'uuid';

function issueAccessToken(userId, scopes) {
  // VULNERABLE: jti generated but never stored anywhere
  return jwt.sign(
    { sub: userId, scopes, jti: uuidv4() },
    process.env.JWT_ACCESS_SECRET,
    { expiresIn: '15m' }
  );
}

// VULNERABLE: jwt.verify checks signature and expiry, not revocation
function requireAuth(req, res, next) {
  const token = req.headers.authorization?.split(' ')[1];
  const payload = jwt.verify(token, process.env.JWT_ACCESS_SECRET);
  req.user = payload;
  next();
}

// Logout — VULNERABLE: only deletes session in DB; issued JWTs still valid
app.post('/auth/logout', requireAuth, async (req, res) => {
  await db.sessions.delete({ userId: req.user.sub });
  res.json({ ok: true }); // token is still valid for up to 15 more minutes
});
// FIXED — jti stored in Redis on issue; checked on every request; deleted on revoke
import jwt from 'jsonwebtoken';
import { v4 as uuidv4 } from 'uuid';
import { createClient } from 'redis';

const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();

const JTI_PREFIX = 'jti:';

async function issueAccessToken(userId, scopes) {
  const jti = uuidv4();
  const expiresInSeconds = 15 * 60; // 15 minutes
  const token = jwt.sign(
    { sub: userId, scopes, jti, typ: 'access' },
    process.env.JWT_ACCESS_SECRET,
    { expiresIn: expiresInSeconds, algorithm: 'HS256' }
  );
  // Store jti in Redis with TTL matching token expiry
  // Key presence = token is valid; key absence = revoked or expired
  await redis.setEx(`${JTI_PREFIX}${jti}`, expiresInSeconds, userId);
  return token;
}

async function requireAuth(req, res, next) {
  const token = req.headers.authorization?.split(' ')[1];
  if (!token) return res.status(401).json({ error: 'Unauthorized' });
  try {
    const payload = jwt.verify(token, process.env.JWT_ACCESS_SECRET, {
      algorithms: ['HS256'],
    });
    if (payload.typ !== 'access') return res.status(401).json({ error: 'Invalid token type' });

    // Check JTI is still valid (not revoked)
    const storedUserId = await redis.get(`${JTI_PREFIX}${payload.jti}`);
    if (!storedUserId) {
      return res.status(401).json({ error: 'Token revoked' });
    }
    req.user = payload;
    next();
  } catch (err) {
    res.status(401).json({ error: 'Unauthorized' });
  }
}

// Logout — delete JTI from Redis to immediately revoke the token
app.post('/auth/logout', requireAuth, async (req, res) => {
  await redis.del(`${JTI_PREFIX}${req.user.jti}`);
  await db.sessions.delete({ userId: req.user.sub });
  res.json({ ok: true }); // token is now immediately invalid
});

// Password reset — revoke ALL active JTIs for the user
// (requires storing userId -> Set mapping, or using a per-user Redis set)
async function revokeAllUserTokens(userId) {
  const pattern = `${JTI_PREFIX}*`;
  // In production: maintain a per-user set of JTIs in Redis for efficient revocation
  // e.g. SADD user:tokens:{userId} jti; on revoke: SMEMBERS user:tokens:{userId} -> DEL each
}

AUTH4-003 — Excessive clock skew leeway defeats token expiry enforcement

JWT libraries expose a clockTolerance (or clockSkew) option that adds grace time around the exp and nbf claims during verification. This exists to handle cases where the token-issuing server and the verifying server have minor clock differences. The correct value is 30–60 seconds — enough to cover normal NTP synchronization jitter on modern cloud infrastructure. When a developer notices that tokens are being rejected due to clock drift and sets clockTolerance to 3600 (one hour) rather than fixing the underlying NTP configuration, a 15-minute access token is now effectively valid for 1 hour and 15 minutes. This wipes out most of the security benefit of short-lived tokens and means a stolen token has a much larger exploitation window.

The correct remediation is to fix the NTP synchronization on the affected server, then set clockTolerance to no more than 30 seconds. If clocks genuinely drift by more than 30 seconds, the deployment infrastructure has a configuration problem that should be addressed directly.

// VULNERABLE — 1-hour clock tolerance added as a workaround for NTP drift
import jwt from 'jsonwebtoken';

function requireAuth(req, res, next) {
  const token = req.headers.authorization?.split(' ')[1];
  try {
    const payload = jwt.verify(token, process.env.JWT_ACCESS_SECRET, {
      algorithms: ['HS256'],
      // VULNERABLE: 3600 second tolerance means a 15-minute token is valid for 75 minutes
      // Added because one production server had NTP misconfigured — wrong fix
      clockTolerance: 3600,
    });
    req.user = payload;
    next();
  } catch (err) {
    res.status(401).json({ error: 'Unauthorized' });
  }
}
// FIXED — clock tolerance capped at 30 seconds; NTP drift fixed at infrastructure level
import jwt from 'jsonwebtoken';

function requireAuth(req, res, next) {
  const token = req.headers.authorization?.split(' ')[1];
  if (!token) return res.status(401).json({ error: 'Unauthorized' });
  try {
    const payload = jwt.verify(token, process.env.JWT_ACCESS_SECRET, {
      algorithms: ['HS256'],
      clockTolerance: 30, // 30 seconds max; fix NTP if this causes false rejections
    });
    req.user = payload;
    next();
  } catch (err) {
    if (err.name === 'TokenExpiredError') {
      return res.status(401).json({ error: 'Token expired', code: 'TOKEN_EXPIRED' });
    }
    res.status(401).json({ error: 'Unauthorized' });
  }
}

// Infrastructure fix: ensure chrony or systemd-timesyncd is running and synced
// On Ubuntu/Debian: timedatectl status should show "NTP service: active"
// systemctl enable --now systemd-timesyncd
// timedatectl set-ntp true
// Acceptable clock drift for JWT: < 1 second in practice on cloud VMs with NTP

AUTH4-004 — Missing audience validation allows cross-environment token replay

The aud (audience) claim identifies the intended recipient of the JWT — typically the specific API or service that should accept it. When jwt.verify() is called without an audience option, the library does not validate the aud claim, even if the token carries one. This means a token minted for the staging environment (aud: "skillaudit-staging") will be accepted by the production API server without complaint. In multi-tenant MCP skill deployments, it also means a token issued for one tenant's API endpoint (aud: "org-acme") may be replayed against another tenant's endpoint (aud: "org-globex") if both share the same signing secret — a cross-tenant authentication bypass.

The fix is straightforward: always pass audience as a hard-coded string (not a configuration variable that could be omitted in an environment) to jwt.verify(). The audience value should be specific to the production deployment and should differ from staging and development values. Including issuer validation at the same time is also recommended — it ensures the token was minted by the expected authority.

// VULNERABLE — jwt.verify() called without audience option; staging tokens accepted on prod
import jwt from 'jsonwebtoken';

// Token issued by staging auth service:
// { sub: "user-123", aud: "skillaudit-staging", iss: "auth.staging.skillaudit.dev", ... }

function requireAuth(req, res, next) {
  const token = req.headers.authorization?.split(' ')[1];
  try {
    // VULNERABLE: no audience or issuer check
    // A token for "skillaudit-staging" is accepted on the production server
    const payload = jwt.verify(token, process.env.JWT_ACCESS_SECRET);
    req.user = payload;
    next();
  } catch (err) {
    res.status(401).json({ error: 'Unauthorized' });
  }
}
// FIXED — audience and issuer validated; staging and dev tokens rejected on production
import jwt from 'jsonwebtoken';

// Hard-code the expected audience and issuer for this deployment.
// Do NOT read these from environment variables that might be unset.
const EXPECTED_AUDIENCE = 'skillaudit-prod';
const EXPECTED_ISSUER   = 'https://auth.skillaudit.dev';

function requireAuth(req, res, next) {
  const token = req.headers.authorization?.split(' ')[1];
  if (!token) return res.status(401).json({ error: 'Unauthorized' });
  try {
    const payload = jwt.verify(token, process.env.JWT_ACCESS_SECRET, {
      algorithms: ['HS256'],
      audience: EXPECTED_AUDIENCE,  // rejects tokens with aud: "skillaudit-staging"
      issuer: EXPECTED_ISSUER,       // rejects tokens from staging auth service
      clockTolerance: 30,
    });
    if (payload.typ !== 'access') {
      return res.status(401).json({ error: 'Invalid token type' });
    }
    req.user = payload;
    next();
  } catch (err) {
    if (err.name === 'JsonWebTokenError' && err.message.includes('audience')) {
      // Log cross-environment replay attempt for security monitoring
      logger.warn('JWT audience mismatch — possible token replay', {
        tokenAudience: err.message,
        requestIp: req.ip,
      });
    }
    res.status(401).json({ error: 'Unauthorized' });
  }
}

// Token issuance — always embed aud and iss claims
function issueAccessToken(userId, scopes) {
  return jwt.sign(
    {
      sub: userId,
      scopes,
      jti: uuidv4(),
      typ: 'access',
      aud: EXPECTED_AUDIENCE,
      iss: EXPECTED_ISSUER,
    },
    process.env.JWT_ACCESS_SECRET,
    { expiresIn: '15m', algorithm: 'HS256' }
  );
}

Detection with SkillAudit

SkillAudit's SA-SKL-AUTH4 rule set detects these four patterns through a combination of static analysis on the repository and runtime probe against a sandboxed deployment. The static pass identifies jwt.verify() call sites missing audience, issuer, or algorithms options; locates environment variable assignments for JWT secrets to determine whether access and refresh tokens share a secret value; and flags clockTolerance values above 60 seconds. The runtime pass issues a refresh token to the token endpoint, then replays it against the resource API to verify that AUTH4-001 is not exploitable in the running deployment, independent of what the source code suggests.

Run SA-SKL-AUTH4 on your skill: Paste your MCP skill's GitHub URL at skillaudit.dev to get a full scan. The free tier covers public repositories and returns a shareable security badge.

FindingSeverityVulnerable patternFix
AUTH4-001CriticalShared HMAC secret; no typ claim; refresh token accepted as access tokenSeparate JWT_ACCESS_SECRET / JWT_REFRESH_SECRET; validate typ: 'access' in middleware
AUTH4-002Highjti claim generated but never stored; revoked tokens remain validStore jti in Redis with TTL on issue; check on each request; delete on logout/reset
AUTH4-003MediumclockTolerance: 3600 added to paper over NTP drift; expiry enforcement defeatedFix NTP sync (timedatectl set-ntp true); set clockTolerance: 30
AUTH4-004Highjwt.verify() called without audience option; staging token accepted on prodjwt.verify(token, secret, { audience: 'skillaudit-prod', algorithms: ['HS256'] })