skip to content

AuthenticationServices

AuthenticationServices runs OAuth sign-in in the system browser with ASWebAuthenticationSession, plus Sign in with Apple and passkeys. Interviewers ask how an iOS app signs users in safely.

on this pageshow

explore

questions

6

With ASWebAuthenticationSession, why does an iOS app run its web sign-in there instead of in its own WKWebView, and how does the result come back?

level: juniorimportance: must knowfreq 70%

answer

  1. who owns the browser view
  2. existing Safari login, after a system alert
  3. callback URL into the completion handler
  4. presentationContextProvider before start()
  5. canceledLogin when the member backs out

basics

~20 s

ASWebAuthenticationSession shows the sign-in page in a secure system browser view that can reuse the user's Safari login, and the app never touches the page; the final redirect to the callback URL reaches the app's completion handler.

solid answer

~50 s

A `WKWebView` belongs to the app, which can run script in it and read what the member types, and it lacks the member's Safari login. `ASWebAuthenticationSession` loads the page in a secure view the system presents, and the API hands the app only the outcome. A system alert naming the domain asks the member to continue, and unless the session is ephemeral the page can use the login Safari already holds, so a member signed in to the studio portal may not type anything. You create it with the authorization URL and a callback (a custom scheme, or from iOS 17.4 a `Callback`), set `presentationContextProvider`, and call `start()`. When the page redirects to the callback URL, the sheet closes and the completion handler gets the full URL; if the member cancels, it gets the `canceledLogin` error. Only the app that started the session receives that callback, even when another app registers the same scheme.

code

swift · 32 lines
swift
import AuthenticationServices
import UIKit

@MainActor
final class PortalSignIn: NSObject, ASWebAuthenticationPresentationContextProviding {
    private let window: UIWindow
    init(window: UIWindow) { self.window = window }

    func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
        window
    }

    func signIn(authorizeURL: URL, onCallback: @escaping (URL) -> Void) {
        let handler: ASWebAuthenticationSession.CompletionHandler = { callbackURL, error in
            if let error = error as? ASWebAuthenticationSessionError, error.code == .canceledLogin {
                return  // the member closed the sheet or declined the system alert
            }
            guard let callbackURL else { return }
            onCallback(callbackURL)  // e.g. yogastudio://auth?code=...
        }
        let session: ASWebAuthenticationSession
        if #available(iOS 17.4, *) {
            session = ASWebAuthenticationSession(
                url: authorizeURL, callback: .customScheme("yogastudio"), completionHandler: handler)
        } else {
            session = ASWebAuthenticationSession(
                url: authorizeURL, callbackURLScheme: "yogastudio", completionHandler: handler)
        }
        session.presentationContextProvider = self  // required before start()
        session.start()
    }
}

go deeper

for a junior

Recall the three steps: create the session with a URL and a callback, set the presentation context provider, call start(), then read the callback URL or the canceledLogin error.

for a middle

Explain who owns the page in each option, why the app never sees the password, and how the shared Safari login and the system alert shape what the member sees.

for a senior

Show you handle every error code, keep the session long enough to cancel it, and pick the initializer by release instead of scattering scheme strings across the code.

for a principal

Frame the web-view question as trust: a sign-in page inside the app's own view asks members and identity providers to trust the app with credentials it never needs.

## Why the sign-in page does not live in the app's own web view A membership app that signs people in through a studio's web portal has two ways to show that portal. It can put the page in a **`WKWebView`**, a view the app creates and controls, or it can hand the page to **`ASWebAuthenticationSession`**, the AuthenticationServices class built for exactly this job (available since iOS 12). The difference is who owns the browser: - In a `WKWebView` the app owns everything. It can inject its own scripts into the page, read the username and password fields, and see every cookie the page sets. A member has no way to tell whether the app is behaving, and the view does not share the login the member already has in Safari. - In `ASWebAuthenticationSession` the system presents a **secure browser view**. The class exposes no way to reach into the page: the app supplies the starting URL, and later receives one thing back, the **callback URL** the page redirects to when sign-in finishes. - Because the session can use the browser's existing data, a member already signed in to the portal in Safari can often finish with a single tap. Apple's header puts the member "in control of whether they want to use their existing logged-in session from Safari". The protocol argument for using the system browser at all (the native-app OAuth guidance) is covered with OAuth redirects; this question is about what the iOS API does. ## Creating and starting a session 1. Build the authorization URL. It must use `http://` or `https://`. 2. Create the session with a callback. On iOS 17.4 and later use `init(url:callback:completionHandler:)` with `.customScheme("yogastudio")` or `.https(host:path:)`. Below 17.4, use `init(url:callbackURLScheme:completionHandler:)`, which the SDK marks to be deprecated in favour of the callback initializer. 3. Set **`presentationContextProvider`** to an object adopting `ASWebAuthenticationPresentationContextProviding`, whose `presentationAnchor(for:)` returns the window the sheet should cover. 4. Call **`start()`**. It may be called only once per instance; starting a cancelled session fails, so a retry needs a new session. ## What the member sees - A system alert names the domain and asks whether to continue. Declining it ends the session. - The page loads in the secure view; the member signs in, or is already signed in through the shared login. - When the page redirects to a URL that matches the callback, the browser view dismisses itself. ## Handling the outcome The completion handler has the shape `(URL?, (any Error)?) -> Void`. Check the error first: | Result | What it means | |---|---| | a callback URL, no error | sign-in finished; parse the code or token from the URL as the provider documents | | `canceledLogin` | the member tapped Cancel or declined the system alert | | `presentationContextNotProvided` | no valid `presentationContextProvider` was set when `start()` ran | | `presentationContextInvalid` | the anchor was not eligible, for example a window that is not in a foreground scene | Apple's documentation adds one guarantee that a hand-rolled web view cannot give: the session makes sure **only the calling app's session** receives the callback, even when more than one installed app registers the same callback scheme. ## Lifetime and cancellation - For apps deploying to iOS 13 or later, the session keeps a strong reference to itself after `start()` until it has called the completion handler, so a local variable is enough. Below iOS 13 the app had to hold it. - Keeping a property anyway is still useful: `cancel()` stops the attempt and dismisses the browser view, for instance when the member leaves the screen. - `canStart` (iOS 13.4) reports whether `start()` would succeed without starting anything. ## Common mistakes in review - **Keeping a scheme string in several places.** The callback scheme, the Info.plist entry where one exists, and the redirect URI registered with the provider must agree; one constant avoids a session that never completes. - **Treating every error as a failure banner.** `canceledLogin` is a normal user choice: reset the button quietly instead of showing an error. - **Starting from the wrong window.** In a multi-window iPad app, return the window the member tapped in, not the first window the app finds; Apple's header asks for the anchor closest to where the member started sign-in. - **Reusing a session object.** A retry needs a new instance, because `start()` works only once. ## What stays outside this API `ASWebAuthenticationSession` only drives the browser leg. Generating a PKCE verifier, exchanging the code at the token endpoint and storing the tokens it returns are separate jobs: the PKCE material belongs with the OAuth protocol, and token storage belongs with Keychain Services. Keep the session code small and let those layers do their own work.

  • What happens if you call start() without setting presentationContextProvider?
    On iOS 13 and later the session has nowhere to present its browser view. The completion handler receives the `presentationContextNotProvided` error and no sheet appears. Only apps deploying to releases before iOS 13 had the key window inferred for them.
  • Do you have to keep a strong reference to the session while the member signs in?
    Not for apps deploying to iOS 13 or later: after `start()` the session holds a strong reference to itself until it has called the completion handler. Many apps still keep a property so they can call `cancel()` when the screen goes away.
  • The member cancels and taps Sign in again. Can you call start() on the same session?
    No. `start()` may be called only once per instance, and calling it on a cancelled session fails. Create a new `ASWebAuthenticationSession` for every attempt.

  • A WKWebView with a custom user agent is just as good for the sign-in page.
  • The session hands the app Safari's cookies so it can call the portal's API itself.
  • Without a presentationContextProvider the session falls back to the key window on iOS 17.
  • Cancelling the sheet calls the completion handler with a nil URL and a nil error.
  • Any app that registers the same custom scheme can steal the session's callback.

Assumes the iOS 27.1 SDK with an iOS 17 deployment target; the Callback initializer is iOS 17.4, so older releases use the callbackURLScheme initializer.

open as a page

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?

level: middleimportance: must knowfreq 65%

basics

~10 s

Create 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.

open as a page

In ASWebAuthenticationSession, what does prefersEphemeralWebBrowserSession change, when must you set it, and what does it cost your users?

level: middleimportance: should knowfreq 50%

basics

~20 s

Setting prefersEphemeralWebBrowserSession to true before start() asks the browser neither to use the member's existing browsing data nor to keep what this sign-in creates, so each sign-in starts clean and the member must type credentials again.

open as a page

In AuthenticationServices on iOS 17.4 and later, how does ASWebAuthenticationSession.Callback let a web sign-in finish on an https URL, and what must be set up?

level: middleimportance: should knowfreq 40%

basics

~10 s

From iOS 17.4, init(url:callback:completionHandler:) takes an ASWebAuthenticationSession.Callback; .https(host:path:) ends the session when the page navigates to that host and path, and the host must be associated with the app through a webcredentials associated domain.

open as a page

In AuthenticationServices, a passkey sign-in through ASAuthorizationPlatformPublicKeyCredentialProvider returns an error with no sheet for members who have a passkey on the website; what do you check, and how should the requests be set up?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Passkey requests need the relying party's domain in a webcredentials associated domain, with an apple-app-site-association file listing the app; without it the request returns an error. Then check the relyingPartyIdentifier matches, and that the device actually holds a credential.

open as a page

Under App Review guideline 4.8, which sign-in methods should a membership app offer beside its own web portal, and what does each choice commit the team to?

level: principalimportance: should knowfreq 35%

basics

~20 s

Guideline 4.8 applies only when a third-party or social login sets up the primary account; the app must then also offer an equivalent login that limits data to name and email, allows a private email and skips ad tracking without consent.

open as a page