Claude MCP skill broken authentication via OAuth state parameter CSRF and PKCE bypass in developer login — SA-SKL-AUTH11
MCP skill developer portals use OAuth 2.0 for developer authentication — connecting GitHub, Google, or identity provider accounts to manage skill submissions, audit results, and billing. The OAuth flow has several security-critical parameters designed to prevent CSRF and token interception attacks: the state parameter prevents cross-site request forgery in the authorization redirect, PKCE prevents authorization code interception attacks, the nonce claim prevents ID token replay, and the authorization code flow prevents access token exposure in URLs. SA-SKL-AUTH11 covers four patterns where these protections are either missing or incorrectly implemented in MCP skill developer login flows.
state parameter stored in localStorage instead of server-side session — attacker can initiate their own OAuth flow, capture the callback URL, and redirect the victim to it; victim's session is linked to the attacker's GitHub account (account takeover via CSRF)code_verifier not validated at token exchange endpoint — authorization code intercepted from referrer header, server log, or browser history can be exchanged without the verifier; server issues tokens without checking SHA256(code_verifier) === code_challengenonce claim in ID token not validated after jwt.verify() — attacker obtains a valid ID token from one client and replays it to authenticate at a different tenant using the same IdP; no nonce binding between authorization request and token claimsresponse_type=token) returns access token in URL fragment #access_token=... — readable by any JavaScript on the page, appears in browser history, may be captured by web analytics scripts; XSS on any portal page can steal the token before navigation clears itAUTH11-001 — OAuth state parameter generated but not bound to session
The OAuth 2.0 state parameter is a CSRF token for the authorization redirect. It must be generated by the server, stored in a server-side session before the authorization redirect, and verified on callback. When state is instead stored in localStorage, the binding between the user's browser session and the state value is broken. Any same-domain JavaScript can read localStorage — including injected scripts from stored XSS — and an attacker who controls the value at callback time can feed an arbitrary callback URL to the victim's browser. The concrete CSRF attack: the attacker starts a GitHub OAuth flow on their own account and obtains the authorization code that GitHub would redirect to the registry callback. They then craft a URL /auth/callback?code=ATTACKER_CODE&state=ATTACKER_STATE and trick the victim into visiting it. If the victim has a valid ATTACKER_STATE in their localStorage (because the attacker initiated the flow in a shared browser context, or used a fixation attack), the callback handler links the victim's registry session to the attacker's GitHub identity.
// VULNERABLE — state stored in localStorage
function initiateGitHubOAuth(req, res) {
const state = crypto.randomBytes(16).toString('hex');
// ❌ stored client-side — not bound to this server session
// Frontend sets: localStorage.setItem('oauth_state', state)
const authUrl = `https://github.com/login/oauth/authorize?client_id=${CLIENT_ID}&state=${state}&scope=read:user`;
res.json({ authUrl });
}
function handleGitHubCallback(req, res) {
// ❌ state read from client-supplied body, not from server session
const { code, state } = req.query;
const storedState = req.body.clientState; // sent by frontend from localStorage
if (state !== storedState) return res.status(403).send('State mismatch');
// Exchange code for token — but state validation was client-controlled
exchangeCodeForToken(code).then(token => linkGitHubAccount(req.user, token));
}
CSRF account takeover impact: In a skill registry context, a successful CSRF account takeover means the victim's developer account is now linked to the attacker's GitHub identity. The attacker can then log in to the victim's account using their own GitHub credentials, accessing all submitted skills, audit reports, API keys, and billing information. The attack requires only that the victim click a crafted link while logged in — no session theft, no password needed.
// FIXED — state stored in server-side session
function initiateGitHubOAuth(req, res) {
const state = crypto.randomBytes(32).toString('hex');
// Store in server session — only readable by this user's server-side session
req.session.oauthState = state;
req.session.oauthInitiatedAt = Date.now();
const authUrl = new URL('https://github.com/login/oauth/authorize');
authUrl.searchParams.set('client_id', CLIENT_ID);
authUrl.searchParams.set('state', state);
authUrl.searchParams.set('scope', 'read:user,user:email');
res.redirect(authUrl.toString());
}
function handleGitHubCallback(req, res) {
const { code, state } = req.query;
// Validate state against server-side session — not client-supplied value
if (!req.session.oauthState || state !== req.session.oauthState) {
return res.status(403).send('OAuth state mismatch — possible CSRF');
}
// Check flow freshness — reject callbacks for stale flows
if (Date.now() - req.session.oauthInitiatedAt > 10 * 60 * 1000) {
return res.status(403).send('OAuth flow expired');
}
// Clear state from session before token exchange to prevent replay
delete req.session.oauthState;
delete req.session.oauthInitiatedAt;
exchangeCodeForToken(code).then(token => linkGitHubAccount(req.user, token));
}
AUTH11-002 — PKCE code_verifier not validated on token exchange
PKCE (Proof Key for Code Exchange, RFC 7636) prevents authorization code interception attacks. The client generates a random code_verifier, computes code_challenge = BASE64URL(SHA256(code_verifier)), and sends the challenge with the authorization request. When exchanging the code for tokens, the client sends the original code_verifier; the authorization server verifies that BASE64URL(SHA256(code_verifier)) matches the stored challenge. If the token exchange endpoint accepts authorization codes without checking the code_verifier, an attacker who obtains an authorization code — from a referrer header leak when the callback URL is in a request to an external resource, from a server access log, or from browser history — can call the token endpoint directly and receive valid access and refresh tokens. The attacker never needed the code_verifier because the server never asked for it.
// VULNERABLE — token exchange ignores code_verifier
app.post('/oauth/token', async (req, res) => {
const { code, grant_type, redirect_uri } = req.body;
// ❌ code_verifier presence and validity not checked
if (grant_type !== 'authorization_code') return res.status(400).json({ error: 'unsupported_grant_type' });
const authRecord = await db.authorizationCodes.findOne({ code });
if (!authRecord || authRecord.expiresAt < Date.now()) {
return res.status(400).json({ error: 'invalid_grant' });
}
// Issues tokens without verifying code_verifier against stored code_challenge
const accessToken = generateAccessToken(authRecord.userId);
res.json({ access_token: accessToken, token_type: 'Bearer' });
});
PKCE is required, not optional: RFC 9700 (OAuth 2.0 Security Best Current Practice) requires PKCE for all public clients and strongly recommends it for confidential clients. If a developer portal acts as a confidential client (server-side OAuth with a client secret), PKCE still adds an independent layer of protection — the client secret prevents unauthorized token exchange, but PKCE prevents the specific scenario where the authorization code is leaked to a third party who also obtains the client secret. Use both.
// FIXED — PKCE code_verifier validated at token exchange
const crypto = require('crypto');
// At /oauth/authorize — store code_challenge in authorization code record
app.get('/oauth/authorize', async (req, res) => {
const { code_challenge, code_challenge_method, client_id, redirect_uri, state } = req.query;
if (code_challenge_method && code_challenge_method !== 'S256') {
return res.status(400).json({ error: 'transform_algorithm_not_supported' });
}
const authCode = crypto.randomBytes(32).toString('hex');
await db.authorizationCodes.insert({
code: authCode,
userId: req.session.userId,
clientId: client_id,
redirectUri: redirect_uri,
codeChallenge: code_challenge || null, // store if PKCE used
codeChallengeMethod: code_challenge_method || null,
expiresAt: Date.now() + 10 * 60 * 1000
});
res.redirect(`${redirect_uri}?code=${authCode}&state=${state}`);
});
// At /oauth/token — verify code_verifier matches stored code_challenge
app.post('/oauth/token', async (req, res) => {
const { code, code_verifier, grant_type, redirect_uri } = req.body;
const authRecord = await db.authorizationCodes.findOne({ code });
if (!authRecord || authRecord.expiresAt < Date.now()) {
return res.status(400).json({ error: 'invalid_grant' });
}
// If PKCE was used at authorize time, it must be verified at token exchange
if (authRecord.codeChallenge) {
if (!code_verifier) {
return res.status(400).json({ error: 'invalid_grant', error_description: 'code_verifier required' });
}
const computedChallenge = crypto
.createHash('sha256')
.update(code_verifier)
.digest('base64url');
if (computedChallenge !== authRecord.codeChallenge) {
return res.status(400).json({ error: 'invalid_grant', error_description: 'code_verifier mismatch' });
}
}
await db.authorizationCodes.delete({ code }); // single use
const accessToken = generateAccessToken(authRecord.userId);
res.json({ access_token: accessToken, token_type: 'Bearer' });
});
AUTH11-003 — OAuth nonce claim in ID token not validated
The OpenID Connect nonce claim binds an ID token to a specific authentication request and prevents token replay attacks. The client generates a random nonce, includes it in the authorization request, and when the ID token is returned, verifies that the token's nonce claim matches the value sent in the authorization request. If the registry's OIDC callback validates the ID token's signature and expiry but does not check the nonce claim, a replay attack is possible. An attacker who registers their own developer account obtains a valid ID token from the IdP. They then craft a login flow for a victim tenant that uses the same IdP, and replay the attacker's ID token during the callback. Because the signature is valid and the token is not expired, jwt.verify() accepts it. Without nonce validation, the registry cannot distinguish a fresh authentication from a replayed token, and the attacker authenticates as themselves at the victim tenant — or, if the IdP's sub claim matches a different user at the target tenant, as that user.
// VULNERABLE — ID token validated without nonce check
app.get('/auth/oidc/callback', async (req, res) => {
const { code } = req.query;
const tokenResponse = await exchangeCodeForTokens(code);
const { id_token } = tokenResponse;
// ❌ Signature and expiry validated — but nonce claim ignored
const claims = jwt.verify(id_token, getPublicKey(), { algorithms: ['RS256'] });
// claims.nonce exists but is never compared to req.session.oauthNonce
const user = await findOrCreateUser(claims.sub, claims.email);
req.session.userId = user.id;
res.redirect('/dashboard');
});
Cross-tenant ID token replay: Multi-tenant MCP skill registries that allow organizations to bring their own IdP are particularly exposed to nonce replay attacks. If two tenants share the same IdP (common with enterprise SSO providers like Okta or Azure AD), an attacker with a developer account at Tenant A can replay their valid ID token to gain access at Tenant B — provided the target user's sub claim matches or the registry does not scope session creation to a specific tenant. Always validate both nonce and aud (audience) claims.
// FIXED — nonce generated and stored in session, validated after jwt.verify()
app.get('/auth/oidc/start', (req, res) => {
const nonce = crypto.randomBytes(32).toString('hex');
const state = crypto.randomBytes(32).toString('hex');
req.session.oauthNonce = nonce;
req.session.oauthState = state;
const authUrl = new URL(OIDC_AUTHORIZE_ENDPOINT);
authUrl.searchParams.set('client_id', CLIENT_ID);
authUrl.searchParams.set('response_type', 'code');
authUrl.searchParams.set('scope', 'openid email profile');
authUrl.searchParams.set('nonce', nonce); // included in authorization request
authUrl.searchParams.set('state', state);
res.redirect(authUrl.toString());
});
app.get('/auth/oidc/callback', async (req, res) => {
const { code, state } = req.query;
// State check (CSRF protection — see AUTH11-001)
if (!req.session.oauthState || state !== req.session.oauthState) {
return res.status(403).send('State mismatch');
}
const tokenResponse = await exchangeCodeForTokens(code);
const { id_token } = tokenResponse;
const claims = jwt.verify(id_token, getPublicKey(), {
algorithms: ['RS256'],
audience: CLIENT_ID // also validate audience claim
});
// Validate nonce claim against session-stored nonce
if (!req.session.oauthNonce || claims.nonce !== req.session.oauthNonce) {
return res.status(403).send('Nonce mismatch — possible token replay');
}
// Clear nonce and state from session after use
delete req.session.oauthNonce;
delete req.session.oauthState;
const user = await findOrCreateUser(claims.sub, claims.email);
req.session.userId = user.id;
res.redirect('/dashboard');
});
AUTH11-004 — OAuth implicit flow used for skill developer login
The OAuth 2.0 implicit flow (response_type=token) returns the access token directly in the URL fragment after the authorization redirect — for example, https://skillaudit.dev/auth/callback#access_token=eyJ...&token_type=Bearer&expires_in=3600. This was designed for browser-only apps that could not keep a client secret, but it has well-documented security problems. The URL fragment is accessible to all JavaScript running on the callback page via window.location.hash, including third-party analytics scripts, error monitoring scripts, and any script injected via XSS on any page of the developer portal (see SA-SKL-XSS8). The access token also appears in the browser's navigation history and may be recorded by browser extensions or proxy logs. The implicit flow was deprecated in OAuth 2.0 Security Best Current Practice (RFC 9700) in favor of authorization code + PKCE, which keeps the access token server-side and never exposes it in the URL.
// VULNERABLE — implicit flow: access token arrives in URL fragment
// Authorization request uses response_type=token:
// GET /oauth/authorize?response_type=token&client_id=...&redirect_uri=...
// Frontend callback handler reads token from fragment
function handleImplicitCallback() {
const url = new URL(window.location.href);
// ❌ token is in the fragment — readable by any script on this page
const params = new URLSearchParams(url.hash.slice(1));
const accessToken = params.get('access_token');
const expiresIn = params.get('expires_in');
// Token now in memory — but it was briefly in window.location.hash
// Any analytics/error script that ran between navigation and this handler read it
localStorage.setItem('access_token', accessToken); // further mistake
initDashboard(accessToken);
}
Migrating away from implicit flow: Switching from implicit to authorization code + PKCE requires backend support for the token exchange step. The access token is exchanged server-side — the browser only ever holds the short-lived authorization code, which is single-use and bound by PKCE. If the developer portal is a pure SPA without a backend, use a backend-for-frontend (BFF) pattern: a thin server-side proxy handles the OAuth exchange and sets an HttpOnly session cookie. The access token never touches the browser.
// FIXED — authorization code + PKCE flow: access token never in URL
// Step 1: Generate PKCE pair and start authorization code flow
async function startOAuthFlow() {
const codeVerifier = crypto.randomBytes(32).toString('base64url');
const codeChallenge = crypto
.createHash('sha256')
.update(codeVerifier)
.digest('base64url');
// Store verifier server-side (via session API call) or in sessionStorage
sessionStorage.setItem('pkce_verifier', codeVerifier);
const state = crypto.randomBytes(16).toString('hex');
sessionStorage.setItem('oauth_state', state); // acceptable for state if no XSS; prefer server session
const authUrl = new URL(AUTHORIZATION_ENDPOINT);
authUrl.searchParams.set('response_type', 'code'); // authorization code, not token
authUrl.searchParams.set('client_id', CLIENT_ID);
authUrl.searchParams.set('redirect_uri', REDIRECT_URI);
authUrl.searchParams.set('code_challenge', codeChallenge);
authUrl.searchParams.set('code_challenge_method', 'S256');
authUrl.searchParams.set('state', state);
window.location.href = authUrl.toString();
}
// Step 2: Exchange code server-side — access token never in URL or client
// GET /auth/callback?code=AUTH_CODE&state=... (code in query param, not fragment)
app.get('/auth/callback', async (req, res) => {
const { code, state } = req.query;
// State validation (server-side session, see AUTH11-001)
if (state !== req.session.oauthState) return res.status(403).send('CSRF check failed');
const codeVerifier = req.session.pkceVerifier; // retrieved from server session
const tokenResponse = await fetch(TOKEN_ENDPOINT, {
method: 'POST',
body: new URLSearchParams({ grant_type: 'authorization_code', code, code_verifier: codeVerifier, redirect_uri: REDIRECT_URI, client_id: CLIENT_ID })
}).then(r => r.json());
// Set HttpOnly session cookie — access_token never sent to browser directly
req.session.accessToken = tokenResponse.access_token;
res.redirect('/dashboard');
});
Detection summary
| Finding | Severity | Attack surface | Fix |
|---|---|---|---|
| AUTH11-001 | CRITICAL | OAuth state in localStorage | Server-side session for state + crypto.randomBytes(32) |
| AUTH11-002 | CRITICAL | Token exchange without PKCE verify | Store code_challenge at authorize; verify SHA256(code_verifier) at exchange |
| AUTH11-003 | HIGH | OIDC nonce not validated | Compare claims.nonce to req.session.oauthNonce post-verify |
| AUTH11-004 | HIGH | Implicit flow token in URL fragment | Migrate to authorization code + PKCE; use BFF pattern for SPAs |
SkillAudit scans MCP skill developer portal authentication flows for all four AUTH11 patterns. OAuth callback handlers that read state from client-supplied values rather than server-side sessions, token exchange endpoints that do not check code_verifier, OIDC callback handlers that call jwt.verify() without a subsequent nonce comparison, and authorization requests using response_type=token each trigger AUTH11 findings. See also SA-SKL-AUTH10 for API key scope bypass and service account privilege escalation, and SA-SKL-AUTH9 for race condition vulnerabilities in OAuth2 token exchange.