Sign in with the native Apple sheet
For: an app developer with an iOS or macOS app that shows the native Sign in with Apple sheet.
What it does: the sheet gives the app an ID token. POST /social/apple/id-token verifies it and opens the session, as the Apple callback does.
Before you start
Section titled “Before you start”- Apple sign-in, as in Sign in with Google and Apple.
- The bundle id of the app, for
social.apple.audiences. Social lists the keys.
- Keep
social.idTokenon. It is on by default withsocial.apple. - Add the bundle id of the app to
social.apple.audiences. - Post
{}toPOST /social/apple/id-token/nonce. Keepnoncein the app. - Set
providerNonceas thenonceof the Apple ID request of the sheet. - Post
{ idToken, nonce, name }toPOST /social/apple/id-token.nameis the name that the sheet gave. - A native app reads
tokenfrom the answer, and sends it as a bearer token. - In a JavaScript app, call
client.social.idTokenNonceandclient.social.idTokenof the client package in place of the posts.
import { createAuth, type MailPort, type StorageAdapter } from "@authtempo/core";
/** Sign in with Apple on the web, and from the native sheet of the iOS app. */export function createNativeAppleAuth( deps: { storage: StorageAdapter; mail: MailPort; secret: string }, // Tests serve their own key set through this fetch. An app leaves it out. fetchFn?: typeof fetch,) { return createAuth({ baseURL: "https://api.example.com", appURL: "https://app.example.com", trustedOrigins: ["https://app.example.com"], secret: deps.secret, storage: deps.storage, mail: deps.mail, social: { apple: { // The Services ID of the web flow. clientId: "com.example.web", teamId: "TEAMID1234", keyId: "KEYID12345", privateKey: "-----BEGIN PRIVATE KEY-----\n…\n-----END PRIVATE KEY-----", // The bundle id of the iOS app: the audience of a token of the native sheet. audiences: ["com.example.ios"], }, ...(fetchFn ? { fetch: fetchFn } : {}), }, });}import { exportJWK, generateKeyPair, SignJWT } from "jose";import { describe, expect, it } from "vitest";import { call, harness } from "../support/harness.ts";import { createNativeAppleAuth } from "./native-apple.ts";
// A test key set in place of Apple's. No test calls Apple.const { publicKey, privateKey } = await generateKeyPair("ES256");const jwk = { ...(await exportJWK(publicKey)), kid: "test-key", alg: "ES256", use: "sig" };const appleKeys: typeof fetch = async (input) => String(input) === "https://appleid.apple.com/auth/keys" ? Response.json({ keys: [jwk] }) : new Response("not found", { status: 404 });
/** The ID token of the native sheet, signed by the test key. */function sheetToken(claims: Record<string, unknown>): Promise<string> { const now = Math.floor(Date.now() / 1000); return new SignJWT({ iss: "https://appleid.apple.com", aud: "com.example.ios", sub: "apple-user-1", email: "ada@privaterelay.appleid.com", email_verified: true, nonce_supported: true, iat: now, exp: now + 600, ...claims, }) .setProtectedHeader({ alg: "ES256", kid: "test-key" }) .sign(privateKey);}
async function nonceOf(auth: ReturnType<typeof createNativeAppleAuth>) { const res = await call(auth, "POST", "/auth/social/apple/id-token/nonce", {}); return (await res.json()) as { nonce: string; providerNonce: string };}
describe("sign in with the native Apple sheet", () => { it("signs in, and the name of the sheet fills the new user", async () => { const auth = createNativeAppleAuth(harness(), appleKeys); const { nonce, providerNonce } = await nonceOf(auth); // The app sets request.nonce = providerNonce on the ASAuthorizationAppleIDRequest. const idToken = await sheetToken({ nonce: providerNonce }); const res = await call(auth, "POST", "/auth/social/apple/id-token", { idToken, nonce, name: "Ada Lovelace", }); expect(res.status).toBe(200); const { user } = (await res.json()) as { user: { name: string } }; expect(user.name).toBe("Ada Lovelace"); });
it("refuses a token posted with no nonce", async () => { const auth = createNativeAppleAuth(harness(), appleKeys); // requireNonce is on by default, so even a token without nonce_supported needs the nonce. const idToken = await sheetToken({ nonce_supported: false }); const res = await call(auth, "POST", "/auth/social/apple/id-token", { idToken }); expect(await res.json()).toEqual({ error: "invalid_token" }); });});How it behaves
Section titled “How it behaves”- The nonce, the token checks, and the one use of each token are those of Sign in with Google One Tap.
- The token must verify against Apple’s key set, with Apple’s issuer and an
audofclientIdor ofaudiences. - The sheet gives the name to the app, not in the token.
namefills a new user only. It never changes the name of a user that exists. - An Apple token with
nonce_supported: trueand no nonce is refused, also withsocial.idToken.requireNonce: false. - A token lives at most one day. Core refuses a token whose
expis more than 86400 seconds after itsiat. - The account rules, the gate of the second factor, and the anonymous upgrade are those of the Apple callback.
- The limits:
id-token-nonce:ip60 andid-token:ip30, each per 15 minutes.
Residuals
Section titled “Residuals”- With
requireNonce: false, a token with no nonce and nononce_supportedskips the hash check. A party that holds only such a token can sign in. KeeprequireNonceon. - Apple’s page of the nonce did not load when the route was written. Core’s tests use test keys, not real tokens.
Before you go live
Section titled “Before you go live”Run these checks on a real device:
- Sign in once with the native sheet. Give it
providerNonce, and confirm that the token’snonceclaim is that value. - On that token, confirm that
expminusiatis 86400 seconds or less. Core refuses a token with a longer life.
If it fails
Section titled “If it fails”invalid_token: the token did not verify, its nonce does not match or is absent, the nonce is spent, or the token signed in before. Ask for a new nonce and a new token.rate_limited: too many nonces or sign-ins from the IP.email_taken_unverified: an account with the address exists, and Apple did not verify the address.sign_up_closed: the sign-up rule refused a new user.account_banned: an operator banned the account.invalid_body: the body is not JSON, or a field has the wrong type.oauth_failed: the subject (sub) of the token is empty, too long, or holds a control character. Core writes the linesocial.bad_subject.email_required: the token holds no address.sso_required: the address is of a domain that signs in by SSO only. Send the browser to the start URL indetail.hook_refusedandhook_failed: a hook of your app refused the sign-in or threw.conflict: another write changed the user at the same moment. Ask for a new nonce and a new token, and try again.