Skip to content

Latest commit

 

History

History
698 lines (552 loc) · 49 KB

EXAMPLES.md

File metadata and controls

698 lines (552 loc) · 49 KB

Examples

This document provides code examples for using the Auth0 UI Components SDK.

Table of Contents

Initialization

Initialize with Auth0.plist

The simplest way to initialize the SDK is using the Auth0.plist configuration file and providing a token provider:

import SwiftUI
import Auth0UniversalComponents

@main
struct MyApp: App {
    init() {
        Auth0UniversalComponentsSDKInitializer.initialize(tokenProvider: YourTokenProvider())
    }
    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

Initialize Programmatically

You can also initialize the SDK programmatically by providing required keys and token provider:

import SwiftUI
import Auth0UniversalComponents

@main
struct MyApp: App {
    init() {
        Auth0UniversalComponentsSDKInitializer.initialize(session: URLSession = .shared,
                                                   bundle: Bundle = .main,
                                                   domain: "your-auth0-domain",
                                                   clientId: "your_client_id",
                                                   audience: "https://your-auth0-domain.auth0.com/me/",
                                                   tokenProvider: YourTokenProvider())
    }
    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

Token Provider Implementation

If initializing programmatically, you need to implement a token provider:

import Auth0
import Auth0UniversalComponents

struct YourTokenProvider: TokenProvider {
    func fetchCredentials() async throws -> Credentials {
        // custom logic to fetch credentials
    }

    func storeCredentials(credentials: Credentials) {
        // custom logic to store credentials
    }

    func store(apiCredentials: APICredentials, for audience: String) {
        // custom logic to store API credentials
    }

    func fetchAPICredentials(audience: String, scope: String) async throws -> APICredentials {
        // custom logic to fetch API credentials
    }
}

Authentication Methods Management

Display Authentication Methods View

Once initialized, you can present the authentication methods management view to allow users to view and manage their MFA authenticators:

import SwiftUI
import Auth0UniversalComponents

struct SettingsView: View {
    var body: some View {
        NavigationView {
            List {
                NavigationLink(destination: MyAccountAuthMethodsView()) {
                    Label("Authentication Methods", systemImage: "lock.shield")
                }
            }
            .navigationTitle("Account Settings")
        }
    }
}

Using MyAccountAuthMethodsView

The MyAccountAuthMethodsView component allows users to:

  • View enrolled authenticators - See all configured MFA methods including:
    • TOTP (Time-based One-Time Password) from authenticator apps
    • Push notifications
    • Email
    • SMS
    • Recovery codes
    • Passkeys (FIDO2/WebAuthn) - Requires iOS 16.6+, macOS 13.5+, visionOS 1.0+
  • Enroll in new authentication methods - Add additional authentication factors
  • Delete authentication methods - Remove enrolled authenticators
  • Manage recovery codes - Generate and manage backup codes for account recovery

Embedded Login

Note: Embedded Login is in beta and requires Auth0.swift 4.0.0-beta.3 or later 4.x, the first release with the Embedded Authorization APIs for signing in with a password and for the multi-factor steps (Guardian push, phone, email and authenticator app codes, and recovery codes). Your tenant must have Embedded Login enabled, with Email OTP, SMS OTP, a username and password, or any of them on the connection you pass in.

Display the Embedded Login View

EmbeddedLoginView runs the full native sign-in flow inside your app: email or phone number entry, then the one-time code (sent by email or text message), then multi-factor authentication (Guardian push, a code by text message, call or email, the code from an authenticator app, or a recovery code) when the tenant's policy asks for more. It reads ClientId and Domain from Auth0.plist. The SDK stores nothing: when the user is signed in it hands the credentials to onAuthenticated, once, on the main actor, and your app keeps them where it keeps its session:

import SwiftUI
import Auth0
import Auth0UniversalComponents

struct LoginView: View {
    @State private var isSignedIn = false
    private let credentialsManager = CredentialsManager(authentication: Auth0.authentication())

    var body: some View {
        NavigationStack {
            EmbeddedLoginView(connection: "email") { credentials in
                // The SDK keeps nothing: this app decides where the credentials go.
                try? credentialsManager.clear()      // drop an earlier session's pinned expiry
                try credentialsManager.store(credentials: credentials)
                isSignedIn = true
            }
        }
        .fullScreenCover(isPresented: $isSignedIn) {
            HomeView()
        }
    }
}

onAuthenticated runs once, as soon as the user is signed in, and after any multi-factor step. If it throws (for example, the Keychain write fails), the user sees an error screen, and Try again restarts from the screen where the email or phone number was entered, because the code has already been used. Call clear() before store when you replace an earlier session: Auth0.swift keeps the previous session's pinned expiry until clear(), so a new sign-in could otherwise be judged expired. The credentials are yours, so never log them.

Customize the Entry Screen

The first screen of EmbeddedLoginView and EmbeddedSignupView is built from pieces you can set: a logo, a title, the field with Continue, the link to the other flow ("Sign up" or "Log in"), and the other ways to continue. Set them on any view above the login:

EmbeddedLoginView(connection: "Username-Password-Authentication") { credentials in
    // …
}
.embeddedEntryLogo {
    Image("BrandLogo")
        .resizable().scaledToFit()
        .frame(height: 48)
        .accessibilityLabel("Acme")
}
.embeddedEntryMessages(EmbeddedEntryMessages(loginOrSignUpTitle: "Welcome to Acme", signUpAction: "Join"))

embeddedEntry(_:) sets everything at once, including the colour of the links.

The logo comes from the theme. Out of the box the entry screens show the Auth0 logo. To show yours on every screen that has a logo, set it once in the theme's brand tokens, together with the label VoiceOver reads:

var theme = Auth0Theme()
theme.brand = DefaultAuth0BrandTokens(logo: Image("AcmeLogo"), logoLabel: "Acme")

ContentView()
    .auth0Theme(theme)

A logo is drawn as a template image, in the text colour, so it reads in dark mode too. Give yours .renderingMode(.original) to keep its own colours. .embeddedEntryLogo { … } replaces the logo on one screen, and .embeddedEntryLogo(.hidden) takes it off. The colour of the "Sign up" and "Log in" links is the theme's colors.foreground.linkPrimary; set it with DefaultAuth0ForegroundColorTokens(linkPrimary:).

To place the pieces yourself, give a layout. It gets each piece as a view, or nil when there is none (no logo set, or sign-up not offered):

let layout = EmbeddedEntryLayout { parts in
    VStack(spacing: 24) {
        HStack { parts.logo; Spacer() }     // the logo on the left, instead of above the title
        parts.title
        parts.form                          // the field and Continue stay together
        parts.accountLink
        parts.alternatives
        Spacer()
    }
}

EmbeddedLoginView(connection: "…") { _ in }
    .embeddedEntryLayout(layout)

EmbeddedEntryLayout.centered (the default) puts the block in the middle of the screen, and .top starts it at the top.

To keep the login to signing in, pass signup: .hidden: the first screen then has no sign-up link, and the login tells the server nothing about sign-up.

Sign up with an Email

EmbeddedSignupView creates a new account: the user enters their email, confirms it with a one-time code, and the account is created. It uses the same Auth0.plist as the login, and hands the credentials to onAuthenticated once, as EmbeddedLoginView does:

struct CreateAccountScreen: View {
    let credentialsManager: CredentialsManager

    var body: some View {
        EmbeddedSignupView(connection: "Username-Password-Authentication") { credentials in
            // Replace any earlier session: Auth0.swift keeps its pinned session expiry until `clear()`.
            try? credentialsManager.clear()
            try credentialsManager.store(credentials: credentials)
            // Route to your signed-in screen.
        }
    }
}
  • EmbeddedLoginView already links to this flow when the tenant offers sign-up, so a button of your own is only needed to start sign-up from somewhere else.
  • The server decides what it asks for. A connection that requires something this view can't ask for yet shows "Sign-up isn't available".
  • If the email already has an account, the server signs that user in, and onAuthenticated is called the same way.
  • A wrong code stays on the code screen. Too many wrong codes, or too many codes requested, end the sign-up with Start over.

Sign up with a Phone Number

The same EmbeddedSignupView signs a user up with a phone number when the connection takes one: nothing changes in your code. The user picks a country and enters the number. A number that takes both a text and a call then asks "Choose how to get your code": Text message or Voice call, and Continue sends it. A number that takes only one is sent the code at once, by text, or by call when it only takes calls. The code screen shows the number as the server masked it, with Edit, and Resend Code once the wait is over, which sends it the same way again.

  • A connection that requires a phone number and allows an email starts on the phone number.
  • A code that timed out stays on the screen with "The code expired. Send a new one to continue." and Resend Code comes on at once. A new code starts the sign-up again for the same number, so the user doesn't type it again.
  • A number the server rejects stays on the entry screen with "Please enter a valid phone number."

Sign up with an Email and a Phone Number

When the connection asks for both, the same EmbeddedSignupView shows one form with an Email and a Phone number field; nothing changes in your code. Each field is marked * (required) or "(Optional)". Continue is on once every required field is valid and any optional one that is filled is valid too.

  • Continue sends the first identifier (required before optional, email before phone) and asks for its code. The other is held on the device: once the code is verified it is sent without a tap, and its code is asked for next. A phone that takes both a text and a call asks which first.
  • The account is created when the server says every required identifier is verified, and the credentials go to onAuthenticated once. If the optional one is left empty, that is right after the first code.
  • An optional field is left out by leaving it empty and tapping Continue. Once an optional identifier has been sent, its code is verified; to go on without it, tap Edit, clear the field and Continue.
  • Edit (or Back) on a code screen returns to the form with what was typed. A verified identifier is shown greyed and read-only there and is never sent again; only a value that changed is sent, and when nothing did, Continue returns to the code screen it left without sending anything.
  • A value the server turns down when it is sent for the user brings them back to the form, with the message under the field.
  • If an Edit reaches the server (the new value is sent) and its code can't be sent or the server turns the value down, the code the user had is gone: typing the old value back sends it again instead of returning to the old code screen. A lost connection before the server answers keeps the code the user holds.
  • Each code screen names what it verifies ("Verify your email", "Verify your phone number"), so the second code screen is a new screen for VoiceOver, which moves to its heading.
  • If the code of the second identifier times out after the first was verified, the sign-up ends with Start over, since a new code would start it again.
  • When the first code is verified and the other identifier's screen comes next, a toast at the top says "Email verified" (or "Phone number verified") over it. There is none when the code creates the account at once.

Say "Account created" on Your Next Screen

The sign-up ends on your app's screen, so the SDK can't say the account was created there. Pass onAccountCreated to EmbeddedSignupView (or to EmbeddedLoginView, for an account created from its "Sign up" link) and show the toast yourself. It is called on the main actor, once, right after onAuthenticated took the credentials, and only for a new account: not for a sign-in, not when the server signed an existing account in, not when the second identifier's code belonged to an existing account (the server signs that user in, whichever identifier it was), not for a sign-up started over after "couldn't be saved", and not when onAuthenticated threw. The view hands credentials over once, so create a new EmbeddedSignupView for each sign-up.

Keep the message somewhere both screens can reach, and show it with .auth0Toast(_:edge:) on the screen the user lands on. A toast set while that screen is being pushed appears once it is on screen:

@MainActor
final class ToastCenter: ObservableObject {
    @Published var message: Auth0ToastMessage?
}

// The signed-in screen:
struct HomeScreen: View {
    @EnvironmentObject private var toasts: ToastCenter

    var body: some View {
        Text("Welcome")    // your signed-in content
            .auth0Toast($toasts.message)
    }
}

// The sign-up, below the same `.environmentObject(toastCenter)`:
struct CreateAccountScreen: View {
    @EnvironmentObject private var toasts: ToastCenter
    let credentialsManager: CredentialsManager
    let showHome: () -> Void    // pushes `HomeScreen`

    var body: some View {
        EmbeddedSignupView(connection: "Username-Password-Authentication", onAccountCreated: {
            toasts.message = Auth0ToastMessage("Account created")
        }, onAuthenticated: { credentials in
            try credentialsManager.store(credentials: credentials)
            showHome()
        })
    }
}

Sign in with a Phone Number

When the connection offers SMS OTP, EmbeddedLoginView signs users in with a code sent by text message, or read out in a voice call. Nothing changes in your code: the screens follow what the tenant offers.

  • Email and phone offered: the first screen asks for whichever the tenant lists first, with Continue with Phone (or Continue with Email) below an OR divider. That button opens the other method's own screen, and Back returns to the first one.
  • Only one offered: the first screen asks for just that one.
  • The phone field starts on the device's country (else the United States), with a picker for the rest. Numbers are formatted as they're typed where a country has a format (US: (423)353-0900), checked on the device ("Please enter a valid phone number."), and sent in E.164 form (+14233530900).
  • The code screen shows the number as the server masked it (From (4**)***-*900), with Edit to change it.
  • A number that takes texts and calls is asked first: Choose how to get your code shows Text message and Voice call side by side, in the order the server lists them (the first is selected), and Continue sends the code the way chosen. The code screen then reads From (4**)***-*900 for a text and Calling (4**)***-*900 for a call. Resend Code repeats the way the code was sent (it reads Call again for a call), and Back from the code returns to the choice. A password the server also offers stays under Continue.
  • A number that takes only one of the two is sent its code at once, with no choice to make. When the password leads, the button for the code says how it will go: Text me a code or Call me with a code, whichever way the server lists first for the number.
  • An expired texted or called code stays on the code screen: Verify is disabled and Resend Code works at once. An expired email code still shows the full-screen error.

A registered phone can also be a multi-factor step; see below.

Sign in with a Password

When the connection offers a password, EmbeddedLoginView signs users in with it. Nothing changes in your code: the screens follow what the tenant offers, which can be one of two shapes.

  • After the email or phone number (the usual shape). The first screen asks for the email or number as before. Once the server has it, it lists what can follow, and the screens follow that order: whatever it lists first leads, and the other is one tap away.

    • A code listed first (what a database connection such as Username-Password-Authentication answers) is sent at once and the screen opens on code entry. When a password is listed too, OR and a Continue with a password button (with a password icon) sit under Resend and open the password screen.
    • A password listed first opens the password screen and nothing is sent. When a code is listed too, OR and an Email me a code button (Text me a code for a number, each with its icon) sit under Continue; it sends the code and opens code entry.
    • Only one of the two is used with no alternative shown.

    Either way the first screen has no password option of its own, and you can switch back and forth. Asking for a code again from the password screen waits as long as Resend does after the last code (the button counts down), so switching can't send one on every tap. A password asked for from the code screen opens the sign-in again, so the code that was sent can't be used afterwards.

    • To choose instead of following the server, pass preference. .server (the default) follows the order above; .code always leads with the code and .password with the password, when the server offers both:

      EmbeddedLoginView(connection: "Username-Password-Authentication", preference: .password) { credentials in
          try session.store(credentials)
      }
  • From a username. If the server's first answer includes a username step, the first screen lists Continue with Password (or Continue with Email, Continue with Phone) below an OR divider, and that button opens a username screen followed by the password screen. With only a username offered, the first screen asks for it.

The same password screen serves both:

  • It shows who is signing in (the email, number or username) in a read-only row under the title, with the label the field had (Email, Phone number or Username) above it and Edit at the end of the row to change it. The password is hidden as it's typed, with a button to show it, and it's offered to iCloud Keychain AutoFill (which needs your app's Associated Domains set up). Continue shows progress while the password is checked, and the code button shows it while a code is sent. The screen keeps its shape either way, on this screen and on the code screen.
  • A wrong password stays on the screen with "Incorrect username or password. Please try again." The field is emptied, so a rejected password can't be sent twice by a second tap. The message is the same when the server offers no password step for a username, so it never tells an account that exists from one that doesn't. The code, when it was offered, stays available; it starts the sign-in again, because the server offers only the password after a wrong one. If the server no longer offers a password when Continue with a password is tapped, the screen returns to the email with "A password isn't available for this account. Please use a code instead."
  • Too many attempts shows "Too many attempts. Please try again later." on the same screen. The server ends the sign-in when it limits you, so the next password (or Email me a code) quietly opens a new one; it never ends on a technical error.
  • A breached password, one that appears in a data breach, can't be used to sign in. A screen says why and Try again returns to the password, where a new password opens a new sign-in. On the code screen, too many wrong codes (or a timeout) ends the sign-in; the next Verify says "This code is no longer valid. Please request a new one." and Resend is available at once.
  • Short of room. The password and code screens scroll when the keyboard or large text leaves too little space (a drag dismisses the keyboard), so OR and the other button stay reachable on a small phone.
  • If the policy asks for more, the password hands over to multi-factor authentication exactly as a one-time code does; see below. The credentials reach onAuthenticated once, after the last step.

Two things to know when you adopt this:

  • Password sign-in is always on. The login tells the server it can render a password, so a connection that offers both a code and a password lists both. Pass a connection that offers only what you want shown, or use preference to choose which leads.
  • The password and username screens are internal for now: use them through EmbeddedLoginView.
  • There's no Forgot password? or Sign up in this flow yet. Auth0.swift has no embedded password reset, so send users who forgot their password to your own screen.

Multi-Factor Authentication

When the tenant's MFA policy asks for more than the one-time code, EmbeddedLoginView moves into MFA in place. MFA is a separate engine, whose decisions are pure logic with no UI, with its own screens, so the login only hands over and takes the result back. It runs Guardian push, SMS (a code texted to a registered phone), voice (a code read out in a call to it), email (a code sent to a registered address), the code from an authenticator app, and a recovery code. With more than one on offer (several devices, several phones, a phone that takes both texts and calls, or several kinds) the user picks one from a list first. Push is listed first, because an approval on a registered device can't be phished and a typed code can; the authenticator app comes next, because its code never travels over the phone network; then a text, a call and an email, in that order, and the recovery code is last. Other factors aren't supported in this flow yet.

  • Approved, or the right code: the credentials go to onAuthenticated. If the policy asks for another factor, the list returns with One more step.
  • SMS and voice: the code is texted, or the call is made, as soon as the factor starts. The list shows the number as the server masked it, with every hidden digit as a small, top-aligned * (also when the server hides digits with X). The code screen says Sent to the phone number ending in 900 for a text (the digits the server shows, up to four; We texted a code to your phone. when it shows none) and Calling your phone number ending in 900 for a call (We're calling your phone with a code. when it shows none); phoneCodeChallenge.text.description and .voice.description reword them. A wrong code stays on the screen with "Invalid Code. Please double check the code sent to your phone."; Resend Code sends a new one the same way after a 60 second wait, and that wait holds if the user leaves with Verify another way and picks the same phone again: the code that was sent is shown again instead of a second one, unless a push, another code or an authenticator app's code went out in between, which replaces it. A code that timed out stays on the screen with Verify off and Resend Code open at once. A dropped connection while checking or resending a code, or a resend the server refuses, shows a message and keeps the screen, because the code already on the phone still works. Too many wrong codes ends the flow. A phone is offered once for each way it can take a code.
  • Email: the code is emailed as soon as the factor starts. The list and the code screen show the address as the server masked it, and it works like the SMS and voice codes: a wrong code stays on the screen with "Invalid Code. Please double check the code sent to your email.", Resend Code sends a new one after a 60 second wait that holds if the user leaves with Verify another way and picks the same address again (unless a push, another code or an authenticator app's code went out in between, which replaces it), a code that timed out stays with Verify off, a dropped connection keeps the screen, and too many wrong codes ends the flow. An address the sign-in's own email code already used is listed too when the tenant offers it: whether that counts as another factor is the tenant's policy.
  • Authenticator app: the code screen is up as soon as the factor starts, with nothing sent first, because the app makes the code. There is no Resend Code. A wrong code stays on the screen with "Invalid Code. Please double check the code in your authenticator app." and the next code can be typed at once. A dropped connection while a code is checked shows a message and keeps the screen: the same code can be sent again. Too many wrong codes ends the flow. Checking a code, right or wrong, replaces any text, call or emailed code sent earlier in the sign-in, so picking that phone or address afterwards sends a new code instead of showing the old one. The factor is offered once, when the server asks for an authenticator app's code, and a user whose only factor is an authenticator app gets this screen, not noEligibleFactors.
  • Recovery code: the field is empty when the factor starts; nothing is sent until the user types or pastes a code and taps Continue (the eye shows what was typed). Before it is sent the code is cleaned: invisible characters that come with pasted text (zero-width spaces, direction marks) and the whitespace around it are removed, while case, hyphens and inner spaces are sent as typed. A wrong code stays with "Invalid recovery code. Please check it and try again."; the message goes as soon as the field changes. Once a code is accepted it is used up, so the screen shows the new one with a copy button and a note to store it somewhere safe: a brief "Copied" bubble confirms the copy, Continue stays off until the user ticks "I have saved this recovery code", and then confirms it and signs the user in. On iOS and visionOS the copy stays on the device and leaves the pasteboard after two minutes; on macOS it is marked concealed for clipboard managers but is not removed. A dropped connection while checking or confirming keeps the screen; any other failure ends the flow. Known limitation in this beta: a check that has already gone out can't be recalled, and it uses the code up, so if the user taps Back while it runs, the new code is never shown. Wait for Continue to stop spinning before leaving.
  • Denied, expired, session ended, too many attempts or no connection: a screen with its own message and Start over, which begins a new sign-in at the first screen, with what was typed there filled in.
  • Verify another way (more than one factor on offer) returns to the list. Back cancels MFA and returns to the first screen; a push approved after that is discarded and never signs the user in.
  • No factor this flow can run (e.g. nothing enrolled, or only a factor this flow doesn't run yet): without a handler, a Verification method not available. screen with Sign in again shows. With .onMfaError, your app is told. Return .handled when it takes over and routes the user itself, or .notHandled when it only observes (logging), so the screen still shows.

Fall back to Universal Login

.onMfaError reports every way MFA can end without signing the user in, except a cancel (the user is still in the login). The one most apps act on is MfaError.noEligibleFactors:

struct SignInScreen: View {
    @EnvironmentObject private var session: SessionStore

    var body: some View {
        EmbeddedLoginView(connection: "email") { credentials in
            try session.store(credentials)       // the flow is complete; the SDK kept nothing
        }
        .onMfaError { error -> MfaErrorHandling in
            // Log or measure the error here: that alone does not take the screen away.
            guard case .noEligibleFactors = error else { return .notHandled }   // the other endings show their own screen
            // This account has no factor the native flow can run. Universal Login supports every factor.
            Task { await session.signInWithUniversalLogin() }
            return .handled
        }
    }
}

extension SessionStore {
    /// Both sign-in paths end here: the app keeps the credentials and marks the user signed in.
    func store(_ credentials: Credentials) throws {
        try? credentialsManager.clear()
        try credentialsManager.store(credentials: credentials)
        didSignIn()
    }

    func signInWithUniversalLogin() async {
        do {
            let credentials = try await Auth0.webAuth()
                .scope("openid profile email offline_access")
                .start()
            try store(credentials)
        } catch {
            // The user closed the browser sheet: they stay on the login, which still offers Back.
        }
    }
}

While your app moves on, the user sees a spinner, not an error. Return .handled only when your app really takes over: if a handler that only logs said .handled, the user would be left on a spinner with no way to cancel. The answer matters only for noEligibleFactors; every other ending has its own screen with a way out. To react to every case, switch over MfaError and include @unknown default; later releases may add cases. See "Handling MFA errors" in the documentation for what each case means.

Change the words

Pass an MfaConfiguration to change the words, replace a screen, or draw everything yourself. MfaMessages is a typed tree: change only the lines you care about and the rest keep their defaults. Text that depends on a value, such as the device name, is a function. A device with no name uses pushChallenge.descriptionUnnamed.

let mfa = MfaConfiguration(
    messages: .default.with {
        $0.authenticatorList.headers.challengeAdditional.title = "Almost there"
        $0.pushChallenge.description = { device in "Approve the request on \(device)." }
        $0.pushChallenge.title = String(localized: "mfa.push.title")     // your own localized string
        $0.phoneCodeChallenge.text.description = { number in "We texted a code to \(number)." }
        $0.phoneCodeChallenge.voice.row.title = "Phone call"
        $0.emailCodeChallenge.description = { address in "We emailed a code to \(address)." }
        $0.recoveryCodeChallenge.saveDescription = "This code works only once. Keep it for when you lose your device."
        $0.recoveryCodeChallenge.savedConfirmation = "I have stored this code"
        $0.totpChallenge.subtitle = "Open your authenticator app."
    }
)
EmbeddedLoginView(connection: "email", mfa: mfa) { credentials in try session.store(credentials) }

The built-in words are English, and the SDK doesn't read your app's String Catalog. To translate them, set the lines with your own String(localized:) values as above.

Replace one screen

A replaced screen only renders its model and calls its actions, so the timers, polling, cancel and switching keep working underneath.

struct BrandedPushScreen: View {
    let model: PushChallengeModel

    var body: some View {
        VStack(spacing: 16) {
            Text("Approve on \(model.deviceName)").font(.title2)
            ProgressView()
            if model.canResend {
                Button(model.resendAvailableIn > 0 ? "Send again in \(model.resendAvailableIn)s" : "Send again") {
                    model.resend()
                }
                .disabled(model.resendAvailableIn > 0)
            }
            if model.canSwitch { Button("Use another way") { model.switchFactor() } }
            Button("Cancel", role: .cancel) { model.cancel() }
        }
    }
}

let mfa = MfaConfiguration(
    screens: MfaScreens(pushChallenge: .custom { BrandedPushScreen(model: $0) })
)

canResend says whether the server still allows another push. resendAvailableIn is the seconds left before it may be sent, and 0 when it can be tapped now. The flow owns that countdown, so calling resend() early does nothing; a replacement only has to show it (the model is published again each second while it counts down). A replacement is also responsible for its own accessibility.

The phone code screen is replaced the same way, with MfaScreens(phoneCodeChallenge: .custom { BrandedCodeScreen(model: $0) }) and a PhoneCodeChallengeModel. It is used for texted and spoken codes alike: read delivery (.text or .voice) to word it. Call submit(code) with all codeLength digits; isVerifying and isCodeRejected say what to show, and resendAvailableIn works as for push. Also show isCodeExpired (the code timed out: submit does nothing, and resend works at once) and requestError (.network or .tooManyAttempts when a request failed but the code is still usable); the words are phoneCodeChallenge.expiredCode, .noConnection and .tooManyRequests. destination is the masked number with every hidden digit as *.

The email code screen is replaced the same way, with MfaScreens(emailCodeChallenge: .custom { BrandedEmailScreen(model: $0) }) and an EmailCodeChallengeModel. It works like PhoneCodeChallengeModel, with address (the masked address) in place of destination and no delivery; its words are under emailCodeChallenge.

The authenticator app's screen is replaced the same way, with MfaScreens(totpChallenge: .custom { BrandedAppCodeScreen(model: $0) }) and a TotpChallengeModel. It works like PhoneCodeChallengeModel without a destination or a resend, because nothing is sent first: call submit(code) with all codeLength digits, and show isVerifying, isCodeRejected and requestError (.network when the check couldn't reach the server: the same code can be sent again). The words are under totpChallenge: title, subtitle, fieldLabel, verify, invalidCode, noConnection and verifyAnotherWay.

The recovery code screen is replaced with the general form below and a RecoveryCodeChallengeModel: while newCode is nil it takes a code through submit(code); once it is set, show it and call confirm() when the user has saved it. The standard screen holds Continue back until its "I have saved this recovery code" box is ticked; a replacement decides that for itself. isCodeRejected and requestError (.network) say what to show, and the words are under recoveryCodeChallenge: the entry (title, description, fieldLabel, placeholder, invalidCode, continueButton, verifyAnotherWay) and the save step (saveTitle, saveDescription, saveHelper, savedConfirmation, copied, copyCode). newCode is the live recovery code: never log it, and don't print or dump the model or the step, because their descriptions include it.

The factor list and the error screen are replaced the same way, through MfaScreens(authenticatorList:error:). The general form, MfaScreens().replacing(.push) { (model: PushChallengeModel) in … } (or .replacing(.recoveryCode) { (model: RecoveryCodeChallengeModel) in … }), works for any factor whose model type is public; chain it to replace more than one, for example MfaScreens(pushChallenge: …).replacing(.voice) { (model: PhoneCodeChallengeModel) in … } to replace only the voice code's screen.

Draw everything yourself (headless)

The flow still decides everything: which factors to offer, when to poll, when to give up, and when to hand the credentials to your app. It only publishes each step into a stream you create and hold, and you draw it however you like.

struct HeadlessSignIn: View {
    @EnvironmentObject private var session: SessionStore
    @StateObject private var stream = MfaStepStream()                // you own the stream

    var body: some View {
        ZStack {
            EmbeddedLoginView(connection: "email",
                              mfa: MfaConfiguration(presentation: .headless(stream))) { credentials in
                try session.store(credentials)
            }
            if let step = stream.step {                              // nil = nothing to draw
                MyMfaScreens(step: step)
            }
        }
    }
}

struct MyMfaScreens: View {
    let step: MfaStep

    var body: some View {
        switch step {
        case .authenticatorList(let model):
            VStack {
                ForEach(model.rows) { row in Button(row.title) { model.select(row.id) } }
                Button("Cancel") { model.cancel() }
            }
        case .factor(let factorStep):                                // a factor's own screen: cast its model
            if let push = factorStep.model as? PushChallengeModel {
                VStack {
                    Text("Waiting on \(push.deviceName)")
                    Button("Cancel") { push.cancel() }
                }
            } else if let code = factorStep.model as? PhoneCodeChallengeModel {
                VStack {
                    Text(code.delivery == .voice ? "Calling \(code.destination)" : "Code sent to \(code.destination)")
                    // your own code entry: call code.submit(digits) with all code.codeLength digits
                    Button("Cancel") { code.cancel() }
                }
            } else if let email = factorStep.model as? EmailCodeChallengeModel {
                VStack {
                    Text(email.address.isEmpty ? "We emailed you a code" : "Code sent to \(email.address)")
                    // your own code entry: call email.submit(digits) with all email.codeLength digits
                    Button("Cancel") { email.cancel() }
                }
            } else if let recovery = factorStep.model as? RecoveryCodeChallengeModel {
                VStack {
                    if let newCode = recovery.newCode {                  // the code was used up: show its replacement
                        Text(newCode)                                    // never log this
                        Button("I have saved it") { recovery.confirm() } // signs the user in
                    } else {
                        // your own entry: call recovery.submit(typed); show recovery.isCodeRejected
                        if recovery.canSwitch { Button("Verify another way") { recovery.switchFactor() } }
                    }
                    Button("Cancel") { recovery.cancel() }
                    }
            } else if let app = factorStep.model as? TotpChallengeModel {
                VStack {
                    Text("Enter the code from your authenticator app")
                    // your own code entry: call app.submit(digits) with all app.codeLength digits
                    Button("Cancel") { app.cancel() }
                }
            } else {
                ProgressView()
            }
        case .error(let model):
            Button("Start over") { model.leave() }
        case .loading:
            ProgressView()
        @unknown default:
            ProgressView()
        }
    }
}
  • An MfaStep is .loading, .authenticatorList, .error, or .factor(step) for a factor's own screen: read step.factor (for example .push, .totp, .sms, .voice, .email or .recoveryCode) and cast step.model to that factor's model (PushChallengeModel, TotpChallengeModel for .totp, PhoneCodeChallengeModel for both .sms and .voice, EmailCodeChallengeModel for .email, or RecoveryCodeChallengeModel). New factors add no case, so switch with @unknown default. A factor whose model you don't cast falls through to your default branch and draws nothing useful, so add a branch for every factor your tenant uses, and for each new one when you update the SDK.
  • stream.step is nil when there is nothing to draw: before the flow starts, and after it ends signed in, cancelled, or with no factor to use. Your overlay goes away and the login's own screen shows.
  • stream.result is .signedIn or .ended(error) when the flow ends, and goes back to nil when the next flow starts.
  • The login still draws its own background and navigation bar; only the MFA steps are yours.
  • The standard screens (MfaAuthenticatorListScreen, MfaPushChallengeScreen, MfaPhoneCodeChallengeScreen, MfaEmailCodeChallengeScreen, MfaTotpChallengeScreen, MfaRecoveryCodeScreen, MfaErrorScreen, MfaLoadingScreen) can also be used on their own with a model, to keep the look for steps you don't want to redraw.

Multi-step sign-in

A policy that needs several factors shows the list again for each step, headed One more step, all inside one MFA run, for as many steps as the server asks for. The step number is on the models (AuthenticatorListModel.round, MfaFactorStep.round). The credentials reach your app once, at the end.

How the pieces fit

Login, the MFA engine and each factor don't know each other's insides:

  • Login only has a small AdditionalStep contract ("an additional step runs here") and never mentions MFA.
  • The MFA engine (MFA/Core) knows the factor list, rounds, switching, cancel, handing over the credentials and rendering the current step. It names no factor, no login type and no Auth0 type.
  • A factor (MFA/Factors/Push, PhoneCode, EmailCode, Totp and RecoveryCode today) is an id and rank, a session that runs it, a model and screen, its words, and a small transport protocol it defines. Adding one touches no engine file.
  • EmbeddedMfaStep is the only adapter that knows both sides: it reads each factor's eligible factors from the server's response and builds the factors over the sign-in.

A source-level test (ArchitectureTests) fails if a layer starts to mention what it must not know.

Read the Stored Credentials

The SDK stores nothing, so you read back whatever your onAuthenticated closure stored. With the CredentialsManager from the example above:

import Auth0

let credentialsManager = CredentialsManager(authentication: Auth0.authentication())

if credentialsManager.canRenew() {
    let credentials = try await credentialsManager.credentials()
    // Use credentials.accessToken / credentials.idToken
}

Flow Behaviour

  • Recoverable errors appear inline: an invalid code, a code that couldn't be sent, an expired texted code, or too many attempts. The user stays on the current screen; when attempts run out, they can use Resend Code.
  • Other failures go full screen: network or server errors. Try again returns to the step that failed.
  • While a request is in flight, Back and Edit are disabled and repeated submits are ignored. This stops a sign-in from finishing after the screen has been dismissed. During MFA, Back cancels it at once, and an approval already on its way is discarded.
  • Email and phone entry keep what was typed when the user comes back to them: Back or Edit from code entry, Back from push, Try again, or Sign in again. A phone number comes back with its country.
  • Push checks right away when the app returns to the foreground, so approving on the same phone signs in without waiting for the next check.
  • The top bar has a back arrow and a title ("Log in", or "Sign up"), on every screen. From the entry screen it leaves the flow with the environment's dismiss, so it pops the screen from a NavigationStack and closes a sheet or full-screen cover. From sign-up opened from the login, it goes back to the login. Later screens go back a step.

Use the Screens Standalone

Each screen takes plain values and closures, so you can drive it from your own state. Pass isLoading while your request runs: the screens ignore taps and keyboard submits during that time.

import SwiftUI
import Auth0UniversalComponents

struct CustomEmailStep: View {
    @State private var isLoading = false
    @State private var errorMessage: String?

    var body: some View {
        VStack(spacing: 0) {
            LoginNavigationBar(title: "Log in", isBackEnabled: !isLoading) {
                // handle back
            }
            LoginEmailScreen(isLoading: isLoading, errorMessage: errorMessage) { email in
                isLoading = true
                Task {
                    defer { isLoading = false }
                    // send the code to `email`, and set `errorMessage` on failure
                }
            }
        }
    }
}

struct CustomPhoneStep: View {
    @State private var isLoading = false
    @State private var errorMessage: String?

    var body: some View {
        LoginPhoneScreen(isLoading: isLoading, errorMessage: errorMessage) { number in
            // `number` is in E.164 form, e.g. "+14233530900"
            isLoading = true
            Task {
                defer { isLoading = false }
                // text the code to `number`, and set `errorMessage` on failure
            }
        }
    }
}

struct CustomCodeStep: View {
    let sentTo: String                  // an email, or the server's masked number
    @State private var isLoading = false
    @State private var isCodeExpired = false

    var body: some View {
        LoginCodeScreen(
            subtitle: "From \(sentTo)",
            isLoading: isLoading,           // also disables "Edit" while verifying
            isCodeExpired: isCodeExpired,   // Verify off, Resend available at once
            onVerify: { code in /* verify `code` */ },
            onEdit: { /* return to email or phone entry */ },
            onResend: { /* resend the code */ }
        )
    }
}

The other screens and building blocks are also public and work the same way:

  • Screens: LoginLoadingScreen, LoginErrorScreen, LoginSuccessScreen, LoginNoMethodsScreen. LoginErrorScreen scrolls when the text is large.
  • Building blocks: LoginScreenHeader (with isEditEnabled), LoginInputField, LoginCodeField (with isEnabled), LoginPrimaryButton, LoginResendButton (with isAvailableNow).

Toast

Auth0ToastView is a toast: a short message (two lines at most), with an icon if its style has one, on a raised surface. .auth0Toast(_:edge:) shows one over a screen. By default it sits at the top, below the safe area, over the content, and one shows at a time: a new message replaces the current one.

struct ProfileScreen: View {
    @State private var toast: Auth0ToastMessage?

    var body: some View {
        Button("Verify phone") { toast = Auth0ToastMessage("Phone number verified") }
            .auth0Toast($toast)
    }
}
  • Words. Sentence case, no full stop: the object and the result ("Phone number verified"). A toast is for a step that needs no decision. Use inline errors or an error screen for anything the user must read or act on.
  • Time. It slides in, rests 4 s (5 s when the message wraps, at least 6 s while VoiceOver is running), and fades out. A swipe away from its edge, or VoiceOver's escape gesture, dismisses it early. With Reduce Motion on it only fades. Pass duration: to set the rest yourself: it is kept between 0 and 60 s.
  • Edge. Toasts appear at the top by default. .auth0Toast($toast, edge: .bottom) makes the bottom the screen's default, and a message can choose its own, which wins: Auth0ToastMessage("Copied", style: .notice, edge: .bottom). The edge sets where the toast rests, which way it slides in (from below at the bottom), and which swipe dismisses it (down at the bottom, up at the top). One screen can show both, one at a time.
  • Icon. Auth0ToastMessage("Link copied", icon: Image(systemName: "doc.on.doc")) replaces the check, and icon: nil removes it. A template image takes the style's icon colour. VoiceOver doesn't read the icon, so the words must say what it says.
  • Style. Auth0ToastMessage("Copied", style: .notice, edge: .bottom) is a small toast in the brand's primary colours with no icon, at the bottom. .success is the default. Start from either and change what you need, or build your own. Colours are closures that take the theme, so they follow a custom theme and dark mode:
var style = Auth0ToastStyle.success
style.icon = Image(systemName: "exclamationmark.triangle.fill")
style.iconColor = { _ in .orange }
style.layout = .compact          // as big as its words; .card is the design's full-width toast

toast = Auth0ToastMessage("Check your connection", style: style)
  • Screens. The toast belongs to the screen it is on, and goes with it. Set the message on the screen the user lands on, not the one they are leaving.
  • VoiceOver is sent an announcement of the message, and focus stays where it was.
  • Alone. Auth0ToastView("Account created") is the toast with no placement or timing, to use inside your own layout. It takes style: or icon: too.
  • Theme. Colours, type, spacing and radius come from Auth0Theme; the card's sizes are sizes.toastMinHeight and sizes.toastMaxWidth.