With Sign in with Apple in AuthenticationServices, how do you request a member's name and email, and why check getCredentialState(forUserID:completion:) on each launch?
answer
- provider, request, controller, delegate
- requestedScopes and authorizedScopes
- credential.user is the stable key
- authorized, revoked, notFound
- credentialRevokedNotification while running
basics
~10 sCreate an ASAuthorizationAppleIDProvider request with requestedScopes [.fullName, .email], run it through ASAuthorizationController, and keep the credential's user identifier; on launch, getCredentialState(forUserID:completion:) says whether that Apple ID authorization is still authorized, revoked or not found.
solid answer
~40 sSign in with Apple needs the Sign in with Apple capability. `ASAuthorizationAppleIDProvider().createRequest()` gives an `ASAuthorizationAppleIDRequest`; set `requestedScopes = [.fullName, .email]` and pass it to an `ASAuthorizationController` with a delegate and a presentation context provider, then call `performRequests()`. On success the delegate gets an `ASAuthorizationAppleIDCredential`: `user` is the opaque identifier, stable across your developer team, `identityToken` and `authorizationCode` go to your server, and `fullName` and `email` are optional. They hold only what the member chose to share, the email can be a private relay address, and `authorizedScopes` can be a subset of what you asked for. Because the member can revoke the app's authorization outside the app at any time, check `getCredentialState(forUserID:completion:)` (or `credentialState(forUserID:)` with async) at launch: `.authorized` keeps them in, `.revoked` or `.notFound` signs them out. While running, observe `credentialRevokedNotification`.
code
swift · 28 linesimport AuthenticationServices
@MainActor
func startAppleSignIn(delegate: any ASAuthorizationControllerDelegate,
anchor: any ASAuthorizationControllerPresentationContextProviding) {
let request = ASAuthorizationAppleIDProvider().createRequest()
request.requestedScopes = [.fullName, .email]
let controller = ASAuthorizationController(authorizationRequests: [request])
controller.delegate = delegate // weak: the caller keeps the delegate alive
controller.presentationContextProvider = anchor
controller.performRequests()
}
func checkAppleIDOnLaunch(userID: String, signOut: @escaping @Sendable () -> Void) {
ASAuthorizationAppleIDProvider().getCredentialState(forUserID: userID) { state, _ in
switch state {
case .authorized: break
default: signOut() // .revoked, .notFound or any other state; signOut hops to the main actor
}
}
}
func observeRevocation(signOut: @escaping @Sendable () -> Void) -> any NSObjectProtocol {
NotificationCenter.default.addObserver(
forName: ASAuthorizationAppleIDProvider.credentialRevokedNotification,
object: nil, queue: .main
) { _ in signOut() }
}go deeper
Recall the chain of provider, request with requestedScopes, controller with performRequests(), then the delegate receiving an ASAuthorizationAppleIDCredential.
Explain which credential fields are optional, what goes to the server, and how getCredentialState and the revocation notification keep the local session honest.
Handle relay emails and missing names without breaking account creation, hop to the main actor from the state check, and sign out on every non-authorized state.
Decide how Apple ID accounts link to existing studio accounts and how revocation reaches server-side sessions, not just the app's own screen.
## The pieces of a Sign in with Apple request Sign in with Apple, available since iOS 13, uses the same request machinery as every other AuthenticationServices sign-in: - **`ASAuthorizationAppleIDProvider`** creates requests and answers credential-state queries. - **`ASAuthorizationAppleIDRequest`**, from `createRequest()`, carries what you ask for: `requestedScopes`, plus optional `state` and `nonce` strings that your server can match later. - **`ASAuthorizationController`** runs one or more requests. It needs a `delegate` (held weakly) and a `presentationContextProvider` that returns the window for the sheet; `performRequests()` starts it. - **`ASAuthorizationControllerDelegate`** receives `authorizationController(controller:didCompleteWithAuthorization:)` or `authorizationController(controller:didCompleteWithError:)`. When the member closes the sheet, the error is `ASAuthorizationError` with code `.canceled`. The target also needs the Sign in with Apple capability, which adds its entitlement. Apple's sample notes that the member must be signed in to an Apple ID with two-factor authentication. ## Asking for name and email The only scopes the framework defines are **`.fullName`** and **`.email`**. Asking is not receiving: - In the sheet the member can edit their name, pick another address, or **hide their email**, in which case Apple generates a proxy address that forwards to the real one. - `fullName` and `email` on the credential are **optional**: they hold only what the member authorized. Check **`authorizedScopes`**, which can be a subset of the request. - Apple's documentation says the full name is passed directly to your app and is **not included in the identity token**, so the server cannot read it there. Send it to your server yourself, and validate and sanitize it before storing, as Apple advises. - Store name and email whenever they arrive; never write the account setup so that it needs them on every sign-in. ## What to keep and what to send | Credential property | What it is | Where it goes | |---|---|---| | `user` | opaque identifier, stable across your developer team while the member stays connected | stored on the device and on your account record | | `identityToken` | a JWT signed by Apple with issuer, subject, audience and expiry | your server, which verifies it | | `authorizationCode` | short-lived, one-time proof of authorization | your server, which validates it with Apple's identity service | | `fullName`, `email` | only what the member shared | your server, once, when present | Where the device keeps `user` and any session token is a Keychain Services decision, covered with secure storage on iOS. ## Checking the credential state on launch A member can stop using their Apple ID with the yoga-studio app at any time, outside the app. The app finds out by asking: 1. Read the stored `user` identifier at launch. 2. Call **`getCredentialState(forUserID:completion:)`**, or `try await credentialState(forUserID:)`. 3. Act on the state: **`.authorized`** means the member stays signed in; **`.revoked`** means they disconnected the app, and **`.notFound`** means the identifier is not known (the header says an error accompanies this state). Apple's sample signs the member out and shows the sign-in screen for both. 4. The enum has further cases, such as `.transferred`, so give the `switch` a `default` branch that does not quietly treat the member as authorized. The completion block is `@Sendable` and is not documented to run on the main thread; Apple's sample hops to the main queue before touching the UI, and your code should too. ## Revocation while the app is running A launch check does not cover a member who disconnects the app while it is running. **`ASAuthorizationAppleIDProvider.credentialRevokedNotification`** tells the app that the credentials have been revoked and the member should be signed out. Observe it, clear the local session, and route to sign-in. Rechecking the state when the app returns to the foreground is a reasonable extra. ## Common mistakes - Running the controller without a `presentationContextProvider` or with a delegate nobody retains; the controller keeps itself alive until the delegate is called, but a deallocated weak delegate hears nothing. - Treating `email` as always the member's real address, and failing to match relay addresses to accounts. - Expecting the name in the identity token. - Checking the state once at sign-in and never again. - Keying accounts on `email` instead of `user`: the email is optional and can be a relay address.
- Why can't the server read the member's name from the identity token?Apple documents that the full name shared in the system UI is passed directly to the app and is not included in the identity token. The app must send `fullName` to its server itself, and the server should validate and sanitize it before storing.
- What should the app do when credentialRevokedNotification arrives?Apple describes it as a sign that the member's credentials were revoked and they should be signed out. Clear the local session and stored tokens, return to the sign-in screen, and let the server know so it can end server-side sessions too.
- Is credential.user the same identifier in every app you publish?The header says it is stable across the developer team as long as the member stays connected with your app. The value may change after the member disconnects the app, so treat an unfamiliar identifier as a possibly new link.
- The identity token carries the member's full name, so the server reads it there.
- credential.email is always the member's real, verified inbox address.
- Requesting .fullName guarantees fullName is non-nil in the credential.
- The credential state only needs checking once, right after sign-in.
- A .notFound state means a network glitch, so keep the member signed in.