OIDC Account Linking: Email Authority, Identity Keys and Nonces
OIDC Account Linking: Email Authority, Identity Keys and Nonces
Search
Ask the AI

OIDC Account Linking: Email Authority, Identity Keys and Nonces

The site uses Google sign-in, Google One Tap and Microsoft sign-in. The first two are entry points for one provider. Account linking requires full ID-token validation followed by an explicit linking policy.

Providers assert different identity and email information. The local examples and current documentation below separate authentication, email ownership and linking to an existing site account.

What the thing looks like

A WordPress site with its own email-and-password accounts — readers need to comment and receive notifications — plus third-party sign-in layered on top. The goal is unremarkable: a reader who already has an account here should land in that account when they sign in with a provider, not acquire a second one.

The main risk is whether the provider identity can safely be linked to that existing account.

Email claims, authority and account linking

Google’s email_verified alone does not establish current ownership of every address. Google treats Gmail and verified hosted accounts with hd as authoritative. A verified third-party email can have changed owner since Google-account creation and needs another challenge. The retained check below is not a complete auto-link policy.

$emailVerified = $payload['email_verified'] ?? false;
$emailVerified = $emailVerified === true || $emailVerified === 'true'
              || $emailVerified === '1'  || $emailVerified === 1;

if ($email === '' || ! is_email($email) || ! $emailVerified) {
    return new WP_Error('email_not_verified', 'Google email is not verified.');
}

OIDC defines email_verified as Boolean. Accepting strings and integers is an adapter choice, not a protocol requirement. For standard JSON tokens, validate declared types and document any upstream conversion.

Microsoft’s ordinary ID-token claims do not supply a directly interchangeable email_verified guarantee. Its documentation treats email as mutable profile data; use validated identity identifiers for linking.

The linking risk arises when an application treats profile email as account-ownership proof. A concrete takeover depends on account type, registration checks and linking rules. The original claim that any unverified MSA registration can take over an account was not established here and is withdrawn.

The existing Microsoft flow looks up sub within its provider namespace and refuses automatic linking on an email collision. A general OIDC identity key is validated iss + sub; Microsoft multi-tenant mappings may use tid + oid as documented.

// Deliberately NOT the Google behaviour. Microsoft asserts no
// email_verified claim, so an address matching an existing account
// proves nothing and must not grant access to it.
$existing = email_exists($email);
if (is_int($existing) && $existing > 0) {
    return new WP_Error('ms_email_taken', 'That email already belongs to a site account.');
}

Existing users can sign in normally and explicitly link Microsoft from their profile. Independent mailbox verification or an existing authenticated session can also establish control.

Stated generally: linking a third-party identity to an existing account is justified by someone vouching for the address, not by the address matching. No vouching, no linking — create a new account, or make the user prove who they are first.

Under the common tenant, the issuer is not a constant

Every ID-token checklist includes “compare iss“, and most tutorials hand you a hard-coded string to compare against. With Microsoft’s common authority, iss varies by tenant, so a fixed string can never match — and deleting the check because it “doesn’t work” throws away issuer validation entirely.

Validate tenant-specific issuer through trusted discovery alongside key source, allowed algorithms, aud, time, nonce and tenant policy. The retained tid-string comparison is only one check, not complete token validation:

$tid = (string) ($payload['tid'] ?? '');
if ($tid === '' || ! preg_match('/^[A-Za-z0-9\-]{1,64}$/', $tid)) {
    return new WP_Error('invalid_id_token', 'Missing Microsoft tenant claim.');
}
if ((string) ($payload['iss'] ?? '')
        !== sprintf('https://login.microsoftonline.com/%s/v2.0', $tid)) {
    return new WP_Error('invalid_id_token', 'Invalid Microsoft ID token issuer.');
}

Constrain tid by provider format and application policy, and bind it to discovery and key issuer rules. A letters/digits/hyphens regex does not establish a trusted tenant. Distinguish intentionally multi-tenant from single-tenant acceptance.

Trusted JWKS and optional x5c

Google’s oauth2/v1/certs hands you PEM certificates that openssl_verify accepts directly. Microsoft publishes a JWKS, where keys are described as n and e — modulus and exponent.

It is easy to end up writing an RSA public key encoder by hand from there: ASN.1 length prefixes, the leading zero byte when the high bit is set, several dozen lines of code that is unpleasant to debug.

If a selected signing key from trusted JWKS contains valid x5c[0], wrap that DER certificate as PEM. x5c is optional, not universal. Pin trusted discovery, check kid/alg and tenant rules, and use a mature JWK library when x5c is absent.

$keys[(string) $key['kid']] = "-----BEGIN CERTIFICATE-----\n"
    . chunk_split((string) $key['x5c'][0], 64, "\n")
    . "-----END CERTIFICATE-----\n";

RFC 7468 specifies 64-character lines for generators; parser tolerance is a separate implementation property. Keep canonical wrapping for interoperability without asserting untested OpenSSL-version rejection.

Issue and consume nonces on cached pages

This implementation passes a server-issued nonce to Google One Tap. On verification, the server compares the token’s nonce with the request value, then checks its signature, age and used marker. Google’s front-end API lists the parameter as optional; browser transaction binding and atomic consumption are discussed below.

This site’s pages are cached twice over: nginx’s fastcgi_cache in front of PHP, Cloudflare in front of that. A per-request nonce printed into the HTML gets cached and served to every subsequent visitor — one nonce shared by everyone, which is precisely the thing it exists to prevent.

This implementation obtains a nonce from a POST endpoint with no-cache response headers. Actual proxy rules determine POST caching; method alone is not a universal guarantee. Verify that responses avoid shared caches.

Which raises the next problem: that endpoint is public and unauthenticated. Storing the nonce in a transient means anyone can loop on it and write unbounded rows into wp_options, since this site has no object cache and transients land in the database.

The answer is a nonce that signs itself and is never stored:

$body = base64url(json_encode([
    'n' => wp_generate_password(24, false, false),
    't' => time(),
]));
// then an HMAC over that, using the site key, appended

A signature proves nonce origin and time; one-time use still needs atomic consumption and transaction/browser binding. The current get_transient followed by set_transient is not an atomic compare-and-commit. A valid Google token is not a reliable rate limiter, so control issuance and verification capacity too.

This design defers the stateful step to a more expensive access point, reducing storage pressure on the public issuance endpoint.

Diagnose a missing One Tap prompt

When One Tap does not display, inspect scripts, authorised origins, CSP, iframe permissions, browser settings and Google session state. SDK status notifications and FedCM behaviour vary by version.

First, the Google Cloud Console needs Authorised JavaScript origins. A redirect_uri alone is not enough: that is for the redirect flow. One Tap runs through the in-browser GSI client, which validates the origin. Missing it, the prompt silently never shows.

The current Google JS reference marks use_fedcm_for_prompt deprecated and ignored. The original “omitting true silently fails” statement is obsolete; follow the current SDK’s FedCM guidance.

A loaded script and registered callback exclude only some faults. Call order, DOM lifecycle and application state can still be wrong. Inspect SDK status, console and requests before assigning the cause.

Apple sign-in cost and token maintenance

Apple never got wired up, for reasons unrelated to difficulty:

Standard Apple Developer Program membership costs 99 USD per year, with regional pricing and eligible institutional fee waivers. Configure website sign-in under Apple’s account and identifier requirements.

Apple client_secret is an ES256-signed JWT valid for at most about six months. Generate it on demand or renew on a schedule, protecting the key and monitoring expiry and failures. A fixed twice-yearly job is not the only design.

Persist the name returned on initial authorisation; later responses generally omit it. Users can supply updates in the site profile. Apple relay mail also requires registered senders and the specified mail-authentication setup.

What this design gives up

Proof of an existing account adds a step on email collision. Measure its conversion effect rather than describing an unmeasured loss as a result.

A user with another verified login or an existing session can relink a replacement provider account. Otherwise use a controlled recovery flow; manual modification is not universally required.

Stateless issuance reduces database writes but still consumes request and computation capacity. Inspect replay state, atomicity and transaction binding at verification. It is not unfloodable.

One Tap loads only for logged-out visitors, and only once the browser is idle. Keeping third-party script off the critical path is a hard requirement for mobile performance here; the cost is that some visitors never see the prompt at all.

The original design leaves Apple unimplemented. Assess membership, keys, token renewal and user demand before adding it.

Leave a Reply

Scroll down