whitebear
← Docs

Guide · Sign in with Apple · WebCrypto · Supabase Edge Functions ·

Revoking Sign in with Apple when an account is deleted

The whole flow App Store guideline 5.1.1(v) asks for: a fresh authorization code from the app, the ES256 client secret signed with WebCrypto, the token exchange and the revocation, from Supabase Edge Functions, Deno, Node, Bun or Workers.

An app that offers Sign in with Apple and lets people delete their account has to revoke their Apple tokens when they do (App Store Review Guideline 5.1.1(v)). Otherwise the app stays in the person's «Sign in with Apple» list, and the next time they sign in Apple treats them as a returning user: no name, no email. Apple's documentation covers the two endpoints; this is the whole flow, with code for a server that has nothing but fetch and WebCrypto: Supabase Edge Functions, Deno, Node 22+, Bun or Cloudflare Workers.

What you need

From Certificates, Identifiers & Profiles:

What Where
Team ID Top right of the developer account
A key with Sign in with Apple Keys → + → Sign in with Apple, tied to your app's primary App ID. Download the .p8: it can only be downloaded once
Key ID The key's page
Client ID The app's bundle ID. For a website, its Services ID and the Return URL it signs in with

Keep the .p8 in your server's secrets, never in the repository.

The flow

The server can't revoke from the person's Apple ID alone: it needs a token, and the only way to get one is an authorization code. So:

  1. When the person confirms the deletion, the app asks Apple for a fresh code (a Sign in with Apple request with no scopes) and sends it with the deletion request.
  2. The server exchanges the code for a token right away. A code lasts five minutes and works once.
  3. The server deletes the account.
  4. The server revokes the token. The app leaves the person's list.

Exchange before deleting, revoke after: if the deletion fails, nothing has been revoked; if Apple fails, the account is still deleted. Never let the deletion depend on Apple answering.

In the app

import AuthenticationServices

let request = ASAuthorizationAppleIDProvider().createRequest()
request.requestedScopes = []
let controller = ASAuthorizationController(authorizationRequests: [request])
controller.delegate = self
controller.performRequests()

// ASAuthorizationControllerDelegate
func authorizationController(controller: ASAuthorizationController,
                             didCompleteWithAuthorization authorization: ASAuthorization) {
    guard let credential = authorization.credential as? ASAuthorizationAppleIDCredential,
          let data = credential.authorizationCode,
          let code = String(data: data, encoding: .utf8) else { return }
    // send `code` with the deletion request
}

On the web, Sign in with Apple JS gives the same code in authorization.code. Only ask for it when the account was made with Apple.

The client secret

Both endpoints want a client_secret: a JWT signed with the key, ES256, valid at most six months. Sign a new one for each call, valid five minutes, and there is nothing to rotate or store.

const APPLE = 'https://appleid.apple.com';

const b64url = (bytes: Uint8Array) =>
  btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
const part = (o: object) => b64url(new TextEncoder().encode(JSON.stringify(o)));

/** The .p8 file's bytes (PKCS #8). */
function pkcs8(pem: string) {
  const body = pem.replace(/\\n/g, '\n').replace(/-----[^-]+-----/g, '').replace(/\s+/g, '');
  return Uint8Array.from(atob(body), (c) => c.charCodeAt(0));
}

async function clientSecret(teamId: string, keyId: string, p8: string, clientId: string) {
  const key = await crypto.subtle.importKey('pkcs8', pkcs8(p8), { name: 'ECDSA', namedCurve: 'P-256' }, false, ['sign']);
  const iat = Math.floor(Date.now() / 1000);
  const signing = `${part({ alg: 'ES256', kid: keyId })}.${part({ iss: teamId, iat, exp: iat + 300, aud: APPLE, sub: clientId })}`;
  // WebCrypto signs ECDSA as r and s side by side, which is what a JWT carries: no DER to convert.
  const signature = await crypto.subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, key, new TextEncoder().encode(signing));
  return `${signing}.${b64url(new Uint8Array(signature))}`;
}

A JWT library that signs ES256 does the same; this way there is no dependency.

Exchange the code

async function post(path: string, form: Record<string, string>) {
  return fetch(`${APPLE}${path}`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams(form),
    signal: AbortSignal.timeout(15_000),
  });
}

async function exchange(code: string, clientId: string, secret: string, redirectUri?: string) {
  const res = await post('/auth/token', {
    client_id: clientId,
    client_secret: secret,
    code,
    grant_type: 'authorization_code',
    ...(redirectUri ? { redirect_uri: redirectUri } : {}),
  });
  if (!res.ok) return null; // { error: 'invalid_grant' } for a used or expired code
  const t = await res.json();
  if (t.refresh_token) return { token: t.refresh_token, hint: 'refresh_token' };
  if (t.access_token) return { token: t.access_token, hint: 'access_token' };
  return null;
}

The refresh token is the one to revoke: revoking it ends the whole grant. Some web codes come back with an access token only, and revoking that works too.

A code belongs to the client that asked for it: an app's code goes with the bundle ID, a website's with the Services ID and the same Return URL it was asked with. Mixing them gives invalid_client.

Revoke it

async function revoke(token: string, hint: string, clientId: string, secret: string) {
  const res = await post('/auth/revoke', { client_id: clientId, client_secret: secret, token, token_type_hint: hint });
  return res.ok; // 200 with an empty body
}

Put together

const secret = () => clientSecret(TEAM_ID, KEY_ID, P8, BUNDLE_ID);

const grant = code ? await exchange(code, BUNDLE_ID, await secret()).catch(() => null) : null;

await deleteAccount(userId);

if (grant) {
  const done = await revoke(grant.token, grant.hint, BUNDLE_ID, await secret()).catch(() => false);
  console.log('apple revoke', done);
}

When Apple says no

error Usually
invalid_grant The code was used already, or is more than five minutes old: the app should ask for a new one just before sending
invalid_client Wrong key, key ID or team ID, the key doesn't have Sign in with Apple, or the client ID isn't the one that asked for the code
unsupported_grant_type grant_type isn't authorization_code

Log the reason and the status, never the code, the token or the key. And log something every time: a silent failure here looks exactly like a success.

Where we use it

Our apps that offer Sign in with Apple run this when an account is deleted, from a Supabase edge function. It is one file of about 200 lines, copied into each app; we keep it private rather than publish a package for two HTTP calls.

whitebear