Note 15 / Auth / Security / Mobile
Sign in with Apple on the server: verify the nonce, redeem the code early, revoke on account deletion
Why a Sign in with Apple backend needs the nonce check and an immediate authorizationCode exchange, and how to make revoke on deletion best effort without blocking it.
- By
- Trần Thế Anh, Software Engineer
- Published
- Work done
- October 2026, AI Note Taker (NestJS, Postgres, Flutter client)
- Stack
- NestJS 11, Prisma, Postgres, Sign in with Apple REST API, AES-256-GCM, Jest
- Reading
- 7 min, 1,420 words
The audit line read: Apple has no nonce, and deleting an account does not revoke the Apple token. Under it was App Store guideline 5.1.1(v), which requires an app that lets people create an account to let them delete it from inside the app. When I read the backend, both halves were true, and a third problem sat next to them. The sign-in request carried the user’s email and Apple ID from the client, and the server believed both.
This note covers the three server pieces that fixed it: verifying the identity token with its nonce, exchanging the authorization code at sign-in, and revoking at deletion without ever letting a failed revoke block the deletion.
The identity token is checked on the server, or it is not checked
One fix sits underneath the rest. The sign-in endpoint accepted email and appleId in the request body. Anyone could post someone else’s Apple ID. The server now takes only the identity token and verifies it itself.
Verification means: decode the header, require alg to be RS256 and a kid to be present (an alg: none token is rejected before any signature work), fetch Apple’s public keys from the JWKS endpoint and cache them for 24 hours, refetch once if the kid is unknown, then verify the signature. After the signature, check iss equals https://appleid.apple.com, aud is one of the app’s client ids, exp has not passed (60 seconds of clock skew allowed), and sub exists. The sub claim is the stable Apple user id.
What the nonce is for
A signed identity token proves Apple issued it. It does not prove it was issued for this sign-in attempt. Without a nonce, a token captured from one session, say in a log or on a rooted device, can be sent to the server again. With a nonce, the app creates a random value for each attempt, gives Apple its SHA-256, and Apple copies that value into the token’s nonce claim. The server receives the raw nonce from the app, hashes it, and compares.
Apple’s documentation for ASAuthorizationOpenIDRequest.nonce says the value is passed to the identity provider and that you can verify it with the identity token. It does not spell out the hashing convention. In my code the app sends the SHA-256 hex of the nonce to Apple and the raw string to my server.
function assertNonce(claim: string | undefined, rawNonce: string | null | undefined) {
if (rawNonce == null) { // client did not send one
if (NONCE_REQUIRED) throw new Unauthorized('nonce required');
return; // allowed, logged
}
const expected = createHash('sha256').update(rawNonce).digest('hex');
const a = Buffer.from(claim ?? '');
const b = Buffer.from(expected);
if (a.length !== b.length || !timingSafeEqual(a, b)) throw new Unauthorized('bad nonce');
}
Two details matter. The comparison is constant-time, and the length is checked first because Node’s timingSafeEqual throws on buffers of unequal length. And null has to mean “not sent” exactly like undefined, since a JSON body can carry an explicit null; a mutation that broke that case turned a test red.
The nonce is optional for now. A missing nonce is accepted with a log line unless the environment flag APPLE_NONCE_REQUIRED is set, so the check can be made mandatory once every client sends one. Until then, a replayed token from a client that sends no nonce is not stopped by this check. The spec covers seven nonce cases: correct, wrong, claim missing, comparing against the raw nonce instead of its hash, missing without the flag, null without the flag, and missing with the flag.
The authorization code lives for a few minutes, so redeem it at sign-in
The reason for the second half is how Apple revoke works. Apple’s revoke endpoint needs the user’s refresh token or access token. You obtain those by sending the authorization code, the short-lived value the app gets next to the identity token, to Apple’s token endpoint. Apple’s technote on account deletions (TN3194) says the revoke endpoint is the only way to invalidate a user’s tokens for your developer account without user interaction, and that you need a valid refresh or access token for it. If you do not have one, the technote says to complete the deletion anyway and revoke by other means.
So the sign-in request has to bring the authorizationCode too, and the server has to redeem it right then. The code is short-lived (Apple’s current reference calls it “a short-lived token”; my notes say five minutes and single use, a figure I did not find on the current Apple pages). Deletion can happen weeks later, long after the code is useless. The exchange is a form POST to Apple’s token endpoint with grant_type=authorization_code, the code, the client id and a client secret. The client secret is a short ES256 JWT that the server signs with the team’s private key: iss the team id, sub the client id, aud https://appleid.apple.com, and a five-minute expiry.
Three guards sit around the exchange:
- The response must contain a
refresh_token. Apple returns it on a code exchange and not when a refresh token is validated. - The
subin the response’sid_tokenmust equal the Apple id I just verified. Without that, a client could verify its own identity token and attach someone else’s code. - The call has an 8 second timeout.
The refresh token is encrypted with AES-256-GCM, with the user id bound in as additional authenticated data, and kept in a separate table (v1:iv:tag:data). A separate table keeps the credential out of every user object a login response serialises. It has no soft-delete column on purpose, so deleting is a real delete.
The exchange runs after the session is issued, in the background, and never throws. The user does not wait the 0.3 to 1 second the Apple call can take, and an Apple outage cannot break sign-in. If the server has no team id, key id or private key configured, the capture is skipped and a warning is logged at boot.
Revoke on deletion, and what failure must not do
The account purge calls revokeForUser before it deletes the user. It decrypts the stored token and posts to Apple’s revoke endpoint with the client id, client secret, the token and token_type_hint=refresh_token. Apple documents a 200 with no body once the token is invalid, or if it already was.
The outcome is one of revoked, none (no token stored), skipped (not configured) and failed. The function never throws, and the credential row is removed in a finally block whatever the outcome. A failed revoke writes an error log so someone can follow up by hand. It does not block the deletion. My reasoning is that the user asked to be deleted, and erasing their data should not wait on Apple’s availability. TN3194 describes the same fallback: complete the deletion, then handle the Apple side through the manual routes it lists. Error logs record only the HTTP status and Apple’s error code, never the response body, since a body can echo token material.
The spec for this service has eight tests: the token is stored encrypted; a code that belongs to someone else (sub mismatch) is not stored; missing config skips; captureInBackground never throws; revoke sends the stored token with a timeout and then the row is gone; Apple refusing does not throw and still deletes the secret; Apple hanging or the network down does the same; with no stored token the outcome is none. Removing the nonce check turned four tests red.
What is checked, and what is not
From my notes and the specs: the eight token tests pass, the nonce cases pass, and the mutations above went red and green. I have not rerun them while writing this, because the checkout I read has no node_modules, and the changes were not committed when I wrote the lessons. I have not run a revoke against Apple production from this setup.
One mismatch I found while checking the docs for this article. My code posts to https://appleid.apple.com/auth/token and /auth/revoke. Apple’s current documentation pages for generating tokens and revoking them list /auth/oauth2/v2/token and /auth/oauth2/v2/revoke. I have not verified whether the older paths keep working, or which one the production code should use. That check is on my list before I rely on revoke in production.
Sources: Apple, TN3194 Handling account deletions and revoking tokens for Sign in with Apple (https://developer.apple.com/documentation/technotes/tn3194-handling-account-deletions-and-revoking-tokens-for-sign-in-with-apple); Apple, Generate and validate tokens, Revoke tokens and Creating a client secret (https://developer.apple.com/documentation/accountorganizationaldatasharing/generate-and-validate-tokens); Apple, ASAuthorizationOpenIDRequest nonce and ASAuthorizationAppleIDCredential authorizationCode in the AuthenticationServices documentation.