Skip to content

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.

  1. Keep social.idToken on. It is on by default with social.apple.
  2. Add the bundle id of the app to social.apple.audiences.
  3. Post {} to POST /social/apple/id-token/nonce. Keep nonce in the app.
  4. Set providerNonce as the nonce of the Apple ID request of the sheet.
  5. Post { idToken, nonce, name } to POST /social/apple/id-token. name is the name that the sheet gave.
  6. A native app reads token from the answer, and sends it as a bearer token.
  7. In a JavaScript app, call client.social.idTokenNonce and client.social.idToken of the client package in place of the posts.
Apple with the bundle id of the app
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 } : {}),
},
});
}
The sheet sign-in as a test
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" });
});
});
  • 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 aud of clientId or of audiences.
  • The sheet gives the name to the app, not in the token. name fills a new user only. It never changes the name of a user that exists.
  • An Apple token with nonce_supported: true and no nonce is refused, also with social.idToken.requireNonce: false.
  • A token lives at most one day. Core refuses a token whose exp is more than 86400 seconds after its iat.
  • The account rules, the gate of the second factor, and the anonymous upgrade are those of the Apple callback.
  • The limits: id-token-nonce:ip 60 and id-token:ip 30, each per 15 minutes.
  • With requireNonce: false, a token with no nonce and no nonce_supported skips the hash check. A party that holds only such a token can sign in. Keep requireNonce on.
  • Apple’s page of the nonce did not load when the route was written. Core’s tests use test keys, not real tokens.

Run these checks on a real device:

  1. Sign in once with the native sheet. Give it providerNonce, and confirm that the token’s nonce claim is that value.
  2. On that token, confirm that exp minus iat is 86400 seconds or less. Core refuses a token with a longer life.
  • 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 line social.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 in detail.
  • hook_refused and hook_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.