### Install Auth0.swift with Carthage Source: https://github.com/auth0/auth0.swift/blob/master/README.md Add this line to your Cartfile to include Auth0.swift using Carthage. Bootstrap with --use-xcframeworks for compatibility. ```text github "auth0/Auth0.swift" ~> 2.22 ``` -------------------------------- ### iOS Callback URL Example Source: https://github.com/auth0/auth0.swift/blob/master/README.md An example of configured callback URLs for an iOS app with a specific bundle identifier and Auth0 domain. ```text https://example.us.auth0.com/ios/com.example.MyApp/callback, com.example.MyApp://example.us.auth0.com/ios/com.example.MyApp/callback ``` -------------------------------- ### Get API Credentials with Combine Source: https://github.com/auth0/auth0.swift/blob/master/EXAMPLES.md This example shows how to retrieve API credentials using the Combine framework for reactive programming. It requires storing the subscription to manage its lifecycle. This method is thread-safe. ```swift credentialsManager .apiCredentials(forAudience: "https://example.com/me", scope: "create:me:authentication_methods") .sink(receiveCompletion: { completion in if case .failure(let error) = completion { print("Failed with: \(error)") } }, receiveValue: { apiCredentials in print("Obtained API credentials: \(apiCredentials)") }) .store(in: &cancellables) ``` -------------------------------- ### Install Carthage Dependency Manager Source: https://github.com/auth0/auth0.swift/blob/master/CONTRIBUTING.md Use Homebrew to install Carthage, a dependency manager for Swift projects. This is a prerequisite for setting up the development environment. ```bash brew install carthage ``` -------------------------------- ### Install Xcode Command Line Tools Source: https://github.com/auth0/auth0.swift/blob/master/fastlane/README.md Ensure you have the latest version of the Xcode command line tools installed before proceeding with fastlane installation. ```sh xcode-select --install ``` -------------------------------- ### Install Auth0.swift with Cocoapods Source: https://github.com/auth0/auth0.swift/blob/master/README.md Add this line to your Podfile to include Auth0.swift using Cocoapods. Ensure you are using a compatible version. ```ruby pod 'Auth0', '~> 2.22' ``` -------------------------------- ### Associated Domain Example Source: https://github.com/auth0/auth0.swift/blob/master/README.md An example of the associated domain configuration for a specific Auth0 domain. ```text webcredentials:example.us.auth0.com ``` -------------------------------- ### Example Commit Messages for Auth0 Swift Source: https://github.com/auth0/auth0.swift/blob/master/AGENTS.md Use conventional-style prefixes for commit messages to categorize changes. Examples include 'feat' for new features, 'fix' for bug fixes, 'chore' for maintenance tasks, and 'docs' for documentation updates. ```text feat: add flexible grant type support ``` ```text fix: correct memory leak in ASUserAgent ``` ```text chore: deprecate Management API client ``` ```text docs: update Native to Web feature docs for GA release ``` -------------------------------- ### Log in to an Organization with Combine Source: https://github.com/auth0/auth0.swift/blob/master/EXAMPLES.md Use the Combine framework to log a user into an Auth0 organization. This example demonstrates handling the result using a Combine sink. ```swift Auth0 .webAuth() .organization("YOUR_AUTH0_ORGANIZATION_NAME_OR_ID") .start() .sink(receiveCompletion: { completion in if case .failure(let error) = completion { print("Failed with: \(error)") } }, receiveValue: { credentials in print("Obtained credentials: \(credentials)") }) .store(in: &cancellables) ``` -------------------------------- ### Get all authentication methods Source: https://github.com/auth0/auth0.swift/blob/master/EXAMPLES.md Retrieves a list of all authentication methods configured for the user's account. Requires the `read:me:authentication_methods` scope. ```APIDOC ## Get all authentication methods ### Description Retrieves a list of all authentication methods configured for the user's account. ### Method `getAuthenticationMethods()` ### Parameters None ### Request Example ```swift Auth0.myAccount(token: apiCredentials.accessToken).authenticationMethods.getAuthenticationMethods().start { result in ... } ``` ### Response #### Success Response - `authenticationMethods` (Array) - A list of authentication methods. #### Response Example ```json [ { "type": "totp", "id": "some-id", "identifier": "user@example.com" } ] ``` ``` -------------------------------- ### Retrieve User Information Source: https://github.com/auth0/auth0.swift/blob/master/README.md Fetch the latest user information from the /userinfo endpoint using the access token. This example uses callbacks. ```swift Auth0 .authentication() .userInfo(withAccessToken: credentials.accessToken) .start { result in switch result { case .success(let user): print("Obtained user: \(user)") case .failure(let error): print("Failed with: \(error)") } } ``` -------------------------------- ### Get All Authentication Methods (Async/Await) Source: https://github.com/auth0/auth0.swift/blob/master/EXAMPLES.md Retrieves all authentication methods for the current user using async/await. Requires the `read:me:authentication_methods` scope. ```swift do { let authenticationMethods = try await Auth0 .myAccount(token: apiCredentials.accessToken) .authenticationMethods .getAuthenticationMethods() .start() print("Obtained authentication methods: \(authenticationMethods)") } catch { print("Failed with: \(error)") } ``` -------------------------------- ### Bootstrap Carthage Dependencies Source: https://github.com/auth0/auth0.swift/blob/master/AGENTS.md Install and build Carthage dependencies using xcframeworks. This command is required for development using the Xcode project. ```bash carthage bootstrap --use-xcframeworks ``` -------------------------------- ### Get All Authentication Methods (Combine) Source: https://github.com/auth0/auth0.swift/blob/master/EXAMPLES.md Retrieves all authentication methods for the current user using Combine. Requires the `read:me:authentication_methods` scope. ```swift Auth0 .myAccount(token: apiCredentials.accessToken) .authenticationMethods .getAuthenticationMethods() .start() .sink(receiveCompletion: { if case .failure(let error) = $0 { print("Failed with: \(error)") } }, receiveValue: { print("Obtained authentication methods: \($0)") }) .store(in: &cancellables) ``` -------------------------------- ### Get All Authentication Methods (Completion Handler) Source: https://github.com/auth0/auth0.swift/blob/master/EXAMPLES.md Retrieves all authentication methods for the current user using a completion handler. Requires the `read:me:authentication_methods` scope. ```swift Auth0 .myAccount(token: apiCredentials.accessToken) .authenticationMethods .getAuthenticationMethods() .start { switch $0 { case .success(let authenticationMethods): print("Obtained authentication methods: \(authenticationMethods)") case .failure(let error): print("Failed with: \(error)") } } ``` -------------------------------- ### Bad: Stringly-typed Error, Force-unwrap, Untyped Completion Source: https://github.com/auth0/auth0.swift/blob/master/AGENTS.md This example shows an anti-pattern with stringly-typed errors, force-unwrapping, and an untyped completion handler, which can lead to runtime crashes and difficult debugging. ```swift func getCredentials(completion: @escaping (Any?, Error?) -> Void) { let creds = storage.getCredentials()! // force-unwrap completion(creds, nil) } ``` -------------------------------- ### Example Authentication Log Output Source: https://github.com/auth0/auth0.swift/blob/master/EXAMPLES.md This log output demonstrates a successful authentication flow with redacted sensitive tokens. Sensitive fields like access_token, refresh_token, and id_token are automatically redacted to "redacted". ```text ASWebAuthenticationSession: https://example.us.auth0.com/authorize?..... Callback URL: com.example.MyApp://example.us.auth0.com/ios/com.example.MyApp/callback?... POST https://example.us.auth0.com/oauth/token HTTP/1.1 Content-Type: application/json Auth0-Client: eyJ2ZXJzaW9uI... { "code": "...", "client_id": "...", "grant_type": "authorization_code", "redirect_uri": "com.example.MyApp://example.us.auth0.com/ios/com.example.MyApp/callback", "code_verifier": "..." } HTTP/1.1 200 Pragma: no-cache Content-Type: application/json Strict-Transport-Security: max-age=3600 Date: Wed, 08 Dec 2025 10:30:00 GMT Content-Length: 1024 Cache-Control: no-cache Connection: keep-alive { "access_token": "redacted", "refresh_token": "redacted", "id_token": "redacted", "token_type": "Bearer", "expires_in": 86400 } ``` -------------------------------- ### Run Specific Test Spec via Xcodebuild Source: https://github.com/auth0/auth0.swift/blob/master/AGENTS.md Run a specific test suite or spec file using `xcodebuild` for targeted testing. This example targets the `CredentialsManagerSpec` on an iPhone 16 simulator. ```bash xcodebuild test -project Auth0.xcodeproj \ -scheme Auth0.iOS \ -destination 'platform=iOS Simulator,name=iPhone 16' \ -only-testing:Auth0Tests/CredentialsManagerSpec ``` -------------------------------- ### Migrate signUp to signup and login Source: https://github.com/auth0/auth0.swift/blob/master/V2_MIGRATION_GUIDE.md Use `signup` to create a user and then `login` to authenticate them, replacing the older `signUp` method. ```swift // Before Auth0 .authentication() .signUp(email: email, username: username, password: password, connection: connection, userMetadata: metadata, scope: scope, parameters: ["key": "value"]) .start { result in // ... } // After Auth0 .authentication() .signup(email: email, username: username, password: password, connection: connection, userMetadata: metadata) .start { result in switch result { case .success: Auth0 .authentication() .login(usernameOrEmail: username, password: password, realmOrConnection: connection, scope: scope) .parameters(["key": "value"]) .start { result in // ... } case .failure(let error): // ... } } } ``` -------------------------------- ### Initialize My Account API Client Source: https://github.com/auth0/auth0.swift/blob/master/EXAMPLES.md Instantiate the My Account API client with an access token. Ensure the token has the necessary scopes for the operations you intend to perform. ```swift Auth0.myAccount(token: apiCredentials.accessToken) ``` -------------------------------- ### Web Auth Signup with Parameters Source: https://github.com/auth0/auth0.swift/blob/master/EXAMPLES.md Initiates Web Auth, directing users to the signup page by specifying the 'screen_hint' parameter. This can be combined with 'prompt: login' to always show the authentication page. ```swift Auth0 .webAuth() .parameters(["screen_hint": "signup"]) .start { result in switch result { case .success(let credentials): print("Obtained credentials: \(credentials)") case .failure(let error): print("Failed with: \(error)") } } ``` ```swift do { let credentials = try await Auth0 .webAuth() .parameters(["screen_hint": "signup"]) .start() print("Obtained credentials: \(credentials)") } catch { print("Failed with: \(error)") } ``` ```swift Auth0 .webAuth() .parameters(["screen_hint": "signup"]) .start() .sink(receiveCompletion: { completion in if case .failure(let error) = completion { print("Failed with: \(error)") } }, receiveValue: { credentials in print("Obtained credentials: \(credentials)") }) .store(in: &cancellables) ``` -------------------------------- ### Bootstrap Auth0.swift Dependencies Source: https://github.com/auth0/auth0.swift/blob/master/CONTRIBUTING.md Fetch and build project dependencies using Carthage. This command is essential for setting up the local development environment after cloning the repository. ```bash carthage bootstrap --use-xcframeworks ``` -------------------------------- ### Login with Passkey (Async/Await) Source: https://github.com/auth0/auth0.swift/blob/master/EXAMPLES.md Log the user in using the obtained passkey credential and login challenge with the Auth0 SDK using async/await syntax. This provides a more modern Swift concurrency approach. ```swift do { let credentials = try await Auth0 .authentication() .login(passkey: loginPasskey, challenge: loginChallenge, connection: "Username-Password-Authentication", scope: "openid profile email offline_access") .start() print("Obtained credentials: \(credentials)") } catch { print("Failed with: \(error)") } ``` -------------------------------- ### Login with Passkey (Callback) Source: https://github.com/auth0/auth0.swift/blob/master/EXAMPLES.md Log the user in using the obtained passkey credential and login challenge with the Auth0 SDK. Specify connection, scope, and handle the result. ```swift Auth0 .authentication() .login(passkey: loginPasskey, challenge: loginChallenge, connection: "Username-Password-Authentication", scope: "openid profile email offline_access") .start { result in switch result { case .success(let credentials): print("Obtained credentials: \(credentials)") case .failure(let error): print("Failed with: \(error)") } } ``` -------------------------------- ### Get All Factors Source: https://github.com/auth0/auth0.swift/blob/master/EXAMPLES.md Retrieves all authentication factors associated with the authenticated user. Requires the `read:me:factors` scope. ```swift Auth0 .myAccount(token: apiCredentials.accessToken) .authenticationMethods .getFactors() .start { switch $0 { case .success(let factors): print("Obtained factors: \(factors)") case .failure(let error): print("Failed with: \(error)") } } ``` ```swift do { let factors = try await Auth0 .myAccount(token: apiCredentials.accessToken) .authenticationMethods .getFactors() .start() print("Obtained factors: \(factors)") } catch { print("Failed with: \(error)") } ``` ```swift Auth0 .myAccount(token: apiCredentials.accessToken) .authenticationMethods .getFactors() .start() .sink(receiveCompletion: { if case .failure(let error) = $0 { print("Failed with: \(error)") } }, receiveValue: { print("Obtained factors: \($0)") }) .store(in: &cancellables) ``` -------------------------------- ### Initialize Credentials Manager Source: https://github.com/auth0/auth0.swift/blob/master/EXAMPLES.md Instantiate the Credentials Manager with an authentication instance. This is the first step to using its credential management features. ```swift let credentialsManager = CredentialsManager(authentication: Auth0.authentication()) ``` -------------------------------- ### Sign up with Database Connection Source: https://github.com/auth0/auth0.swift/blob/master/EXAMPLES.md Use this method to sign up a user with a database connection. User metadata can be included. Requires a valid connection name. ```swift Auth0 .authentication() .signup(email: "support@auth0.com", password: "secret-password", connection: "Username-Password-Authentication", userMetadata: ["first_name": "John", "last_name": "Appleseed"]) .start { result in switch result { case .success(let user): print("User signed up: \(user)") case .failure(let error): print("Failed with: \(error)") } } ``` ```swift do { let user = try await Auth0 .authentication() .signup(email: "support@auth0.com", password: "secret-password", connection: "Username-Password-Authentication", userMetadata: ["first_name": "John", "last_name": "Appleseed"]) .start() print("User signed up: \(user)") } catch { print("Failed with: \(error)") } ``` ```swift Auth0 .authentication() .signup(email: "support@auth0.com", password: "secret-password", connection: "Username-Password-Authentication", userMetadata: ["first_name": "John", "last_name": "Appleseed"]) .start() .sink(receiveCompletion: { completion in if case .failure(let error) = completion { print("Failed with: \(error)") } }, receiveValue: { user in print("User signed up: \(user)") }) .store(in: &cancellables) ``` -------------------------------- ### Get an authentication method by id Source: https://github.com/auth0/auth0.swift/blob/master/EXAMPLES.md Retrieves a specific authentication method by its unique identifier. Requires the `read:me:authentication_methods` scope. ```APIDOC ## Get an authentication method by id ### Description Retrieves a specific authentication method by its unique identifier. ### Method `getAuthenticationMethod(by: String)` ### Parameters #### Path Parameters - **id** (String) - Required - The unique identifier of the authentication method. ### Request Example ```swift Auth0.myAccount(token: apiCredentials.accessToken).authenticationMethods.getAuthenticationMethod(by: id).start { result in ... } ``` ### Response #### Success Response - `authenticationMethod` (Object) - The requested authentication method. #### Response Example ```json { "type": "totp", "id": "some-id", "identifier": "user@example.com" } ``` ``` -------------------------------- ### Log in user with Passkey Source: https://github.com/auth0/auth0.swift/blob/master/EXAMPLES.md Completes the signup process by logging in a new user with a created passkey credential and signup challenge. Requires 'openid profile email offline_access' scope. ```swift Auth0 .authentication() .login(passkey: signupPasskey, challenge: signupChallenge, connection: "Username-Password-Authentication", scope: "openid profile email offline_access") .start { result in switch result { case .success(let credentials): print("Obtained credentials: \(credentials)") case .failure(let error): print("Failed with: \(error)") } } ``` ```swift do { let credentials = try await Auth0 .authentication() .login(passkey: signupPasskey, challenge: signupChallenge, connection: "Username-Password-Authentication", scope: "openid profile email offline_access") .start() print("Obtained credentials: \(credentials)") } catch { print("Failed with: \(error)") } ``` ```swift Auth0 .authentication() .login(passkey: signupPasskey, challenge: signupChallenge, connection: "Username-Password-Authentication", scope: "openid profile email offline_access") .start() .sink(receiveCompletion: { completion in if case .failure(let error) = completion { print("Failed with: \(error)") } }, receiveValue: { credentials in print("Obtained credentials: \(credentials)") }) .store(in: &cancellables) ``` -------------------------------- ### Request TOTP Enrollment Challenge (Callback) Source: https://github.com/auth0/auth0.swift/blob/master/EXAMPLES.md Initiates the TOTP enrollment process by requesting an enrollment challenge. Requires the `create:me:authentication_methods` scope. Use this when not using async/await or Combine. ```swift Auth0 .myAccount(token: apiCredentials.accessToken) .authenticationMethods .enrollTOTP() .start { result in switch result { case .success(let enrollmentChallenge): print("Obtained enrollment challenge: \(enrollmentChallenge)") case .failure(let error): print("Failed with: \(error)") } } ``` -------------------------------- ### Get authentication methods by type Source: https://github.com/auth0/auth0.swift/blob/master/EXAMPLES.md Retrieves a list of authentication methods filtered by a specific type. Requires the `read:me:authentication_methods` scope. ```APIDOC ## Get authentication methods by type ### Description Retrieves a list of authentication methods filtered by a specific type. The `type` parameter accepts values from the `AuthenticationMethodType` enum. ### Method `getAuthenticationMethods(type: AuthenticationMethodType)` ### Parameters #### Query Parameters - **type** (`AuthenticationMethodType`) - Required - The type of authentication method to filter by. Possible values: `.password`, `.passkey`, `.webAuthnPlatform`, `.webAuthnRoaming`, `.totp`, `.phone`, `.email`, `.pushNotification`, `.recoveryCode`. Pass `nil` or omit to retrieve all types. ### Request Example ```swift Auth0.myAccount(token: apiCredentials.accessToken).authenticationMethods.getAuthenticationMethods(type: .totp).start { result in ... } ``` ### Response #### Success Response - `authenticationMethods` (Array) - A list of authentication methods of the specified type. #### Response Example ```json [ { "type": "totp", "id": "some-id", "identifier": "user@example.com" } ] ``` ``` -------------------------------- ### Request Passkey Enrollment Challenge (Callback) Source: https://github.com/auth0/auth0.swift/blob/master/EXAMPLES.md Initiate the passkey enrollment process by requesting an enrollment challenge from Auth0. This method uses a callback to handle the result, which can be a success or failure. ```swift Auth0 .myAccount(token: apiCredentials.accessToken) .authenticationMethods .passkeyEnrollmentChallenge() .start { result in switch result { case .success(let enrollmentChallenge): print("Obtained enrollment challenge: \(enrollmentChallenge)") case .failure(let error): print("Failed with: \(error)") } } ``` -------------------------------- ### Request Passkey Enrollment Challenge (Async/Await) Source: https://github.com/auth0/auth0.swift/blob/master/EXAMPLES.md Request an enrollment challenge for passkey creation using async/await syntax. This provides a more modern and sequential way to handle asynchronous operations. ```swift do { let enrollmentChallenge = try await Auth0 .myAccount(token: apiCredentials.accessToken) .authenticationMethods .passkeyEnrollmentChallenge() .start() print("Obtained enrollment challenge: \(enrollmentChallenge)") } catch { print("Failed with: \(error)") } ``` -------------------------------- ### Run All Tests via Swift Package Manager Source: https://github.com/auth0/auth0.swift/blob/master/AGENTS.md Use this command to execute all tests locally using Swift Package Manager. It's the fastest option for local testing. ```bash swift test ``` -------------------------------- ### Log in with database connection Source: https://github.com/auth0/auth0.swift/blob/master/EXAMPLES.md This snippet demonstrates how to log in a user using their username/email and password with a specific database connection. It also shows how to specify custom scopes and handle the result using callbacks, async/await, and Combine. ```APIDOC ## Log in with database connection ### Description Logs in a user with a username or email and password against a database connection. ### Method `login(usernameOrEmail:password:realmOrConnection:scope:)` ### Parameters - **usernameOrEmail** (String) - The username or email of the user. - **password** (String) - The user's password. - **realmOrConnection** (String) - The name of the database connection to use. - **scope** (String) - The scopes to request. Defaults to `openid profile email`. ### Request Example (Callback) ```swift Auth0 .authentication() .login(usernameOrEmail: "support@auth0.com", password: "secret-password", realmOrConnection: "Username-Password-Authentication", scope: "openid profile email offline_access") .start { result in switch result { case .success(let credentials): print("Obtained credentials: \(credentials)") case .failure(let error): print("Failed with: \(error)") } } ``` ### Request Example (async/await) ```swift do { let credentials = try await Auth0 .authentication() .login(usernameOrEmail: "support@auth0.com", password: "secret-password", realmOrConnection: "Username-Password-Authentication", scope: "openid profile email offline_access") .start() print("Obtained credentials: \(credentials)") } catch { print("Failed with: \(error)") } ``` ### Request Example (Combine) ```swift Auth0 .authentication() .login(usernameOrEmail: "support@auth0.com", password: "secret-password", realmOrConnection: "Username-Password-Authentication", scope: "openid profile email offline_access") .start() .sink(receiveCompletion: { completion in if case .failure(let error) = completion { print("Failed with: \(error)") } }, receiveValue: { credentials in print("Obtained credentials: \(credentials)") }) .store(in: &cancellables) ``` ### Notes - The default scope value is `openid profile email`. Regardless of the scope value specified, `openid` is always included. ``` -------------------------------- ### Direct to Signup Page with Web Auth Source: https://github.com/auth0/auth0.swift/blob/master/EXAMPLES.md Add this parameter to the Web Auth configuration to direct users straight to the signup page. ```swift Auth0 .webAuth() .parameters(["login_hint": email, "screen_hint": "signup"]) // ... ``` -------------------------------- ### Enroll MFA Factors Source: https://github.com/auth0/auth0.swift/blob/master/EXAMPLES.md When MFA enrollment is required, you can enroll various types of MFA factors. This example shows how to enroll for SMS-based MFA. ```APIDOC ## Enroll MFA Factors (SMS) ### Description Enroll a phone number for SMS-based MFA. An SMS with a verification code will be sent to the phone number. ### Method Signature `Auth0.mfa().enroll(mfaToken: String, phoneNumber: String) -> APIResponse` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```swift Auth0 .mfa() .enroll(mfaToken: mfaToken, phoneNumber: "+12025550135") .start { // Handle result } ``` ### Response #### Success Response (200) Returns an enrollment challenge object containing the OOB code. - **challenge** (EnrollmentChallenge) - The enrollment challenge object. - **oobCode** (String) - The One-Time-Password (OTP) code to be sent via SMS. #### Response Example ```json { "oobCode": "some_oob_code_here" } ``` ### Error Handling Handles errors during the SMS enrollment process. ``` -------------------------------- ### Request Signup Challenge (Async/Await) Source: https://github.com/auth0/auth0.swift/blob/master/EXAMPLES.md Requests a passkey signup challenge using async/await syntax for modern Swift concurrency. Catches errors using a do-catch block. ```swift do { let signupChallenge = try await Auth0 .authentication() .passkeySignupChallenge(email: "support@auth0.com", name: "John Appleseed", givenName: "John", familyName: "Appleseed", nickname: "johnny", picture: "https://example.com/photo.png", userMetadata: ["signup_source": "ios_app"], connection: "Username-Password-Authentication") .start() print("Obtained signup challenge: \(signupChallenge)") } catch { print("Failed with: \(error)") } ``` -------------------------------- ### Get Authentication Method by ID (Combine) Source: https://github.com/auth0/auth0.swift/blob/master/EXAMPLES.md Retrieves a specific authentication method by its ID using Combine. Requires the `read:me:authentication_methods` scope. ```swift Auth0 .myAccount(token: apiCredentials.accessToken) .authenticationMethods .getAuthenticationMethod(by: id) .start() .sink(receiveCompletion: { if case .failure(let error) = $0 { print("Failed with: \(error)") } }, receiveValue: { print("Obtained authentication method: \($0)") }) .store(in: &cancellables) ``` -------------------------------- ### Login with Passkey (Combine) Source: https://github.com/auth0/auth0.swift/blob/master/EXAMPLES.md Log the user in using the obtained passkey credential and login challenge with the Auth0 SDK using Combine framework. This is suitable for reactive programming styles. ```swift Auth0 .authentication() .login(passkey: loginPasskey, challenge: loginChallenge, connection: "Username-Password-Authentication", scope: "openid profile email offline_access") .start() .sink(receiveCompletion: { completion in if case .failure(let error) = completion { print("Failed with: \(error)") } }, receiveValue: { credentials in print("Obtained credentials: \(credentials)") }) .store(in: &cancellables) ``` -------------------------------- ### Get Authentication Method by ID (Async/Await) Source: https://github.com/auth0/auth0.swift/blob/master/EXAMPLES.md Retrieves a specific authentication method by its ID using async/await. Requires the `read:me:authentication_methods` scope. ```swift do { let authenticationMethod = try await Auth0 .myAccount(token: apiCredentials.accessToken) .authenticationMethods .getAuthenticationMethod(by: id) .start() print("Obtained authentication method: \(authenticationMethod)") } catch { print("Failed with: \(error)") } ``` -------------------------------- ### Get Available Authenticators Source: https://github.com/auth0/auth0.swift/blob/master/EXAMPLES.md Retrieves a list of available MFA authenticators for a user. Use this after an MFA challenge is required, filtering by allowed factors. ```swift // Extract factors from the challenge field of MFA required error payload let factorsAllowed = mfaPayload.mfaRequirements.challenge?.map { $0.type } ?? [] Auth0 .mfa() .getAuthenticators(mfaToken: mfaToken, factorsAllowed: factorsAllowed) .start { switch result { case .success(let authenticators): print("Available authenticators: \(authenticators)") for authenticator in authenticators { print("ID: \(authenticator.id), Type: \(authenticator.authenticatorType)") } case .failure(let error): print("Failed with: \(error)") } } ``` ```swift // Extract factors from the challenge field of MFA required error payload let factorsAllowed = mfaPayload.mfaRequirements.challenge?.map { $0.type } ?? [] do { let authenticators = try await Auth0 .mfa() .getAuthenticators(mfaToken: mfaToken, factorsAllowed: factorsAllowed) .start() print("Available authenticators: \(authenticators)") for authenticator in authenticators { print("ID: \(authenticator.id), Type: \(authenticator.authenticatorType)") } } catch { print("Failed with: \(error)") } ``` ```swift // Extract factors from the challenge field of MFA required error payload let factorsAllowed = mfaPayload.mfaRequirements.challenge?.map { $0.type } ?? [] Auth0 .mfa() .getAuthenticators(mfaToken: mfaToken, factorsAllowed: factorsAllowed) .start() .sink(receiveCompletion: { completion in if case .failure(let error) = completion { print("Failed with: \(error)") } }, receiveValue: { authenticators in print("Available authenticators: \(authenticators)") for authenticator in authenticators { print("ID: \(authenticator.id), Type: \(authenticator.authenticatorType)") } }) .store(in: &cancellables) ``` -------------------------------- ### Log in with Database Connection (Combine) Source: https://github.com/auth0/auth0.swift/blob/master/EXAMPLES.md This snippet demonstrates logging in with a database connection using the Combine framework for reactive programming. Ensure the 'Password' grant type is enabled in your Auth0 application. ```swift Auth0 .authentication() .login(usernameOrEmail: "support@auth0.com", password: "secret-password", realmOrConnection: "Username-Password-Authentication", scope: "openid profile email offline_access") .start() .sink(receiveCompletion: { completion in if case .failure(let error) = completion { print("Failed with: \(error)") } }, receiveValue: { credentials in print("Obtained credentials: \(credentials)") }) .store(in: &cancellables) ``` -------------------------------- ### Retrieve User Credentials Source: https://github.com/auth0/auth0.swift/blob/master/README.md Retrieve stored credentials from the Keychain. The credentials will be automatically renewed if expired using the refresh token. This example uses callbacks. ```swift credentialsManager.credentials { result in switch result { case .success(let credentials): print("Obtained credentials: \(credentials)") case .failure(let error): print("Failed with: \(error)") } } ``` -------------------------------- ### Request Signup Challenge (Callback) Source: https://github.com/auth0/auth0.swift/blob/master/EXAMPLES.md Initiates a passkey signup challenge using email and optional user details. Handles the result via a completion handler. ```swift Auth0 .authentication() .passkeySignupChallenge(email: "support@auth0.com", name: "John Appleseed", givenName: "John", familyName: "Appleseed", nickname: "johnny", picture: "https://example.com/photo.png", userMetadata: ["signup_source": "ios_app"], connection: "Username-Password-Authentication") .start { result in switch result { case .success(let signupChallenge): print("Obtained signup challenge: \(signupChallenge)") case .failure(let error): print("Failed with: \(error)") } } ``` -------------------------------- ### Web Auth Error Handling (Before) Source: https://github.com/auth0/auth0.swift/blob/master/V2_MIGRATION_GUIDE.md Demonstrates the previous error handling for Web Auth methods. ```swift // Before switch result { case .success(let credentials): // ... case .failure(let error as WebAuthError): // handle WebAuthError case .failure(let error): // handle Error } ``` -------------------------------- ### Start Web Authentication with Ephemeral Session Source: https://github.com/auth0/auth0.swift/blob/master/Documentation.docc/WebAuth/UserAgents.md Use this to configure ASWebAuthenticationSession for ephemeral sessions, which do not persist cookies and disable SSO. No consent alert is shown. ```swift Auth0 .webAuth() .useEphemeralSession() .start { result in // ... } ``` -------------------------------- ### Run fastlane ios build_docs Source: https://github.com/auth0/auth0.swift/blob/master/fastlane/README.md Execute this command to generate API documentation for your iOS project. The 'bundle exec' prefix is optional. ```sh [bundle exec] fastlane ios build_docs ``` -------------------------------- ### Get Authentication Method by ID (Completion Handler) Source: https://github.com/auth0/auth0.swift/blob/master/EXAMPLES.md Retrieves a specific authentication method by its ID using a completion handler. Requires the `read:me:authentication_methods` scope. ```swift Auth0 .myAccount(token: apiCredentials.accessToken) .authenticationMethods .getAuthenticationMethod(by: id) .start { switch $0 { case .success(let authenticationMethod): print("Obtained authentication method: \(authenticationMethod)") case .failure(let error): print("Failed with: \(error)") } } ``` -------------------------------- ### Configure Auth0 Client ID and Domain with plist Source: https://github.com/auth0/auth0.swift/blob/master/README.md Create an Auth0.plist file in your app bundle to configure the Client ID and Domain for Auth0.swift. Replace placeholders with your actual Auth0 application credentials. ```xml ClientId YOUR_AUTH0_CLIENT_ID Domain YOUR_AUTH0_DOMAIN ``` -------------------------------- ### Get Authentication Methods by Type (Combine) Source: https://github.com/auth0/auth0.swift/blob/master/EXAMPLES.md Retrieves authentication methods of a specific type (e.g., TOTP) using Combine. Requires the `read:me:authentication_methods` scope. ```swift Auth0 .myAccount(token: apiCredentials.accessToken) .authenticationMethods .getAuthenticationMethods(type: .totp) .start() .sink(receiveCompletion: { if case .failure(let error) = $0 { print("Failed with: \(error)") } }, receiveValue: { print("Obtained TOTP authentication methods: \($0)") }) .store(in: &cancellables) ``` -------------------------------- ### Get Authentication Methods by Type (Async/Await) Source: https://github.com/auth0/auth0.swift/blob/master/EXAMPLES.md Retrieves authentication methods of a specific type (e.g., TOTP) using async/await. Requires the `read:me:authentication_methods` scope. ```swift do { let authenticationMethods = try await Auth0 .myAccount(token: apiCredentials.accessToken) .authenticationMethods .getAuthenticationMethods(type: .totp) .start() print("Obtained TOTP authentication methods: \(authenticationMethods)") } catch { print("Failed with: \(error)") } ``` -------------------------------- ### Enroll Passkey with Auth0 (Completion Handler) Source: https://github.com/auth0/auth0.swift/blob/master/EXAMPLES.md Enrolls a newly created passkey credential with Auth0 using the provided enrollment challenge and an access token. This uses the standard completion handler pattern for asynchronous operations. ```swift Auth0 .myAccount(token: apiCredentials.accessToken) .authenticationMethods .enroll(passkey: newPasskey, challenge: enrollmentChallenge) .start { result in switch result { case .success(let authenticationMethod): print("Enrolled passkey: \(authenticationMethod)") case .failure(let error): print("Failed with: \(error)") } } ``` -------------------------------- ### Start Web Authentication (Default) Source: https://github.com/auth0/auth0.swift/blob/master/Documentation.docc/WebAuth/UserAgents.md By default, Auth0.swift uses ASWebAuthenticationSession without ephemeral sessions. This shares session cookies with Safari and shows a consent alert. ```swift Auth0 .webAuth() .start { result in // ... } ``` -------------------------------- ### Get a Refresh Token with Auth0.swift Source: https://github.com/auth0/auth0.swift/blob/master/EXAMPLES.md Request the `offline_access` scope when logging in to obtain a refresh token from Auth0. Ensure the Auth0 application has the refresh token grant enabled. ```swift Auth0 .webAuth() .scope("openid profile email offline_access read:todos") // ... ``` -------------------------------- ### Migrate webAuth with connection Source: https://github.com/auth0/auth0.swift/blob/master/V2_MIGRATION_GUIDE.md The `webAuth(withConnection:)` method is replaced by initializing `webAuth()` and then using the `connection(_:)` method. ```swift // Before Auth0 .authentication() .webAuth(withConnection: connection) .start { result in // ... } } // After Auth0 .webAuth() .connection(connection) .start { result in // ... } } ``` -------------------------------- ### Start Web Authentication with SFSafariViewController Source: https://github.com/auth0/auth0.swift/blob/master/Documentation.docc/WebAuth/UserAgents.md Configure Auth0.swift to use SFSafariViewController for web authentication. This persists cookies within the app but does not share them externally, enabling app-specific SSO. ```swift Auth0 .webAuth() .provider(WebAuthentication.safariProvider()) .start { result in // ... } ``` -------------------------------- ### Request Signup Challenge (Combine) Source: https://github.com/auth0/auth0.swift/blob/master/EXAMPLES.md Uses the Combine framework to handle passkey signup challenges, subscribing to the publisher for results and completion events. ```swift Auth0 .authentication() .passkeySignupChallenge(email: "support@auth0.com", name: "John Appleseed", givenName: "John", familyName: "Appleseed", nickname: "johnny", picture: "https://example.com/photo.png", userMetadata: ["signup_source": "ios_app"], connection: "Username-Password-Authentication") .start() .sink(receiveCompletion: { completion in if case .failure(let error) = completion { print("Failed with: \(error)") } }, receiveValue: { signupChallenge in print("Obtained signup challenge: \(signupChallenge)") }) .store(in: &cancellables) ``` -------------------------------- ### Get Authentication Methods by Type (Completion Handler) Source: https://github.com/auth0/auth0.swift/blob/master/EXAMPLES.md Retrieves authentication methods of a specific type (e.g., TOTP) using a completion handler. Requires the `read:me:authentication_methods` scope. ```swift Auth0 .myAccount(token: apiCredentials.accessToken) .authenticationMethods .getAuthenticationMethods(type: .totp) .start { switch $0 { case .success(let authenticationMethods): print("Obtained TOTP authentication methods: \(authenticationMethods)") case .failure(let error): print("Failed with: \(error)") } } ``` -------------------------------- ### Get Available Authenticators Source: https://github.com/auth0/auth0.swift/blob/master/EXAMPLES.md Retrieve the list of available authenticators that the user has already enrolled. Use the factors from the `challenge` field of the MFA required error payload to filter the authenticators. ```APIDOC ## Get Available Authenticators ### Description After receiving an MFA token, you can retrieve the list of available authenticators that the user has already enrolled. Use the factors from the `challenge` field of the MFA required error payload to filter the authenticators. ### Method Signature `Auth0.mfa().getAuthenticators(mfaToken: String, factorsAllowed: [String]) -> APIResponse<[Authenticator]>` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```swift // Extract factors from the challenge field of MFA required error payload let factorsAllowed = mfaPayload.mfaRequirements.challenge?.map { $0.type } ?? [] Auth0 .mfa() .getAuthenticators(mfaToken: mfaToken, factorsAllowed: factorsAllowed) .start { // Handle result } ``` ### Response #### Success Response (200) Returns a list of available authenticators. - **authenticators** ([Authenticator]) - A list of available MFA authenticators. #### Response Example ```json [ { "id": "authenticator_id_1", "authenticatorType": "otp", "displayName": "Google Authenticator" }, { "id": "authenticator_id_2", "authenticatorType": "sms", "displayName": "SMS" } ] ``` ### Error Handling Handles errors during the authenticator retrieval process. ``` -------------------------------- ### Log in to an Organization with Async/Await Source: https://github.com/auth0/auth0.swift/blob/master/EXAMPLES.md Perform web authentication to log a user into an Auth0 organization using async/await syntax. Ensure your organization identifier is correctly provided. ```swift do { let credentials = try await Auth0 .webAuth() .organization("YOUR_AUTH0_ORGANIZATION_NAME_OR_ID") .start() print("Obtained credentials: \(credentials)") } catch { print("Failed with: \(error)") } ``` -------------------------------- ### Get API Credentials with Completion Handler Source: https://github.com/auth0/auth0.swift/blob/master/EXAMPLES.md Use this method to obtain API credentials using a completion handler. Ensure you handle potential errors during the process. This method is thread-safe. ```swift credentialsManager.apiCredentials(forAudience: "https://example.com/me", scope: "create:me:authentication_methods") { result in switch result { case .success(let apiCredentials): print("Obtained API credentials: \(apiCredentials)") case .failure(let error): print("Failed with: \(error)") } } ``` -------------------------------- ### Request Passkey Login Challenge Source: https://github.com/auth0/auth0.swift/blob/master/EXAMPLES.md Initiates the passkey login process by requesting a challenge from Auth0. This is the first step in a three-step process. Ensure Passkeys are enabled for your tenant and application. ```swift Auth0 .authentication() .passkeyLoginChallenge(connection: "Username-Password-Authentication") .start { result in switch result { case .success(let loginChallenge): print("Obtained login challenge: \(loginChallenge)") case .failure(let error): print("Failed with: \(error)") } } ``` ```swift do { let loginChallenge = try await Auth0 .authentication() .passkeyLoginChallenge(connection: "Username-Password-Authentication") .start() print("Obtained login challenge: \(loginChallenge)") } catch { print("Failed with: \(error)") } ``` ```swift Auth0 .authentication() .passkeyLoginChallenge(connection: "Username-Password-Authentication") .start() .sink(receiveCompletion: { completion in if case .failure(let error) = completion { print("Failed with: \(error)") } }, receiveValue: { loginChallenge in print("Obtained login challenge: \(loginChallenge)") }) .store(in: &cancellables) ``` -------------------------------- ### Request Passkey Enrollment Challenge (Combine) Source: https://github.com/auth0/auth0.swift/blob/master/EXAMPLES.md Request an enrollment challenge for passkey creation using the Combine framework. This approach is suitable for reactive programming paradigms. ```swift Auth0 .myAccount(token: apiCredentials.accessToken) .authenticationMethods .passkeyEnrollmentChallenge() .start() .sink(receiveCompletion: { completion in if case .failure(let error) = completion { print("Failed with: \(error)") } }, receiveValue: { enrollmentChallenge in print("Obtained enrollment challenge: \(enrollmentChallenge)") }) .store(in: &cancellables) ``` -------------------------------- ### Sign in with Apple using Authorization Code Source: https://github.com/auth0/auth0.swift/blob/master/EXAMPLES.md Use the authorization code from Sign in with Apple to obtain Auth0 credentials. Requires prior setup of the Sign in with Apple flow in your app. ```swift Auth0 .authentication() .login(appleAuthorizationCode: "auth-code") .start { result in switch result { case .success(let credentials): print("Obtained credentials: \(credentials)") case .failure(let error): print("Failed with: \(error)") } } ``` ```swift do { let credentials = try await Auth0 .authentication() .login(appleAuthorizationCode: "auth-code") .start() print("Obtained credentials: \(credentials)") } catch { print("Failed with: \(error)") } ``` ```swift Auth0 .authentication() .login(appleAuthorizationCode: "auth-code") .start() .sink(receiveCompletion: { completion in if case .failure(let error) = completion { print("Failed with: \(error)") } }, receiveValue: { credentials in print("Obtained credentials: \(credentials)") }) .store(in: &cancellables) ``` -------------------------------- ### Handle MFA Required Error with Combine Source: https://github.com/auth0/auth0.swift/blob/master/EXAMPLES.md This example demonstrates how to manage MFA required errors using the Combine framework. It's suitable for applications that leverage reactive programming principles. ```swift Auth0 .authentication() .login(usernameOrEmail: "support@auth0.com", password: "secret-password", realmOrConnection: "Username-Password-Authentication", scope: "openid profile email") .start() .sink(receiveCompletion: { completion in if case .failure(let error as AuthenticationError) = completion, error.isMultifactorRequired, let mfaPayload = error.mfaRequiredErrorPayload { let mfaToken = mfaPayload.mfaToken print("MFA token: \(mfaToken)") if let enrollTypes = mfaPayload.mfaRequirements.enroll { print("User needs to enroll MFA") print("Available enrollment types: \(enrollTypes.map { $0.type })") // Example output: ["otp", "phone", "push-notification"] } if let challengeTypes = mfaPayload.mfaRequirements.challenge { print("User has enrolled MFA factors") print("Available challenge types: \(challengeTypes.map { $0.type })") // Example output: ["otp", "phone"] } } }, receiveValue: { credentials in print("Obtained credentials: \(credentials)") }) .store(in: &cancellables) ```