Authgear
Start BuildingHomePortalCommunity
  • Authgear Overview
  • Get Started
    • Start Building
    • 5-Minute Guide
    • Single-Page App
      • JavaScript (Web)
      • React
      • Angular
      • Vue
    • Native/Mobile App
      • iOS SDK
      • Android SDK
        • Android Kotlin coroutine support
        • Android OKHttp Interceptor Extension (Optional)
      • Flutter SDK
      • React Native SDK
      • Ionic SDK
      • Xamarin SDK
      • Using Authgear without SDK (Client side)
    • Regular Web App
      • Express
      • Next.js
      • Python Flask App
      • Java Spring Boot
      • ASP.NET Core MVC
      • Laravel
      • PHP
    • Backend/API Integration
      • Validate JWT in your application server
      • Forward Authentication to Authgear Resolver Endpoint
    • AI Coding tools
      • Cursor/Windsurf
  • How-To Guides
    • Authenticate
      • Add Passkeys Login
      • Add WhatsApp OTP Login
      • Add Email Magic Link Login
      • Add Biometric Login
      • Add Anonymous Users
      • Add authentication to any web page
      • Enable Two-Factor Authentication (2FA)
      • How to Use the OAuth 2.0 State Parameter
      • Reauthentication
      • How to Use Social/Enterprise Login Providers Without AuthUI
      • Passwordless Login for Apple App Store Review
      • Setup local development environment for Cookie-based authentication
      • Forgot/Reset Password settings
      • Phone number validation
      • Set Password Expiry
    • Single Sign-on
      • App2App Login
      • Pre-authenticated URLs
      • SSO between Mobile Apps / Websites
      • Force Authgear to Show Login Page
      • Single Sign-On with OIDC
      • Single Sign-On with SAML
        • Use Authgear as SAML Identity Provider for Salesforce
        • Use Authgear as SAML Identity Provider for Dropbox
        • SAML Attribute Mapping
    • Social Login / Enterprise Login Providers
      • Social Login Providers
        • Connect Apps to Apple
        • Connect Apps to Google
        • Connect Apps to Facebook
        • Connect Apps to GitHub
        • Connect Apps to LinkedIn
        • Connect Apps to WeChat
      • Enterprise Login Providers
        • Connect Apps to Azure Active Directory
        • Connect Apps to Microsoft AD FS
        • Connect Apps to Azure AD B2C
      • Force Social/Enterprise Login Providers to Show Login Screen
    • Built-in UI
      • Branding in Auth UI
      • User Settings
      • Privacy Policy & Terms of Service Links
      • Customer Support Link
      • Custom Text
    • Custom UI
      • Authentication Flow API
      • Implement Authentication Flow API using Express
      • Implement Authentication Flow API using PHP
      • Add Custom Login/Signup UI to Native Apps
      • Manually Link OAuth Provider using Account Management API
      • Implement a custom account recovery UI using Authentication Flow API
    • Integrate
      • Add custom fields to a JWT Access Token
      • User Analytics by Google Tag Manager
      • Track User Before and After Signup
      • Custom domain
      • Custom Email Provider
      • Custom SMS Provider
        • Twilio
        • Webhook/Custom Script
    • Monitor
      • Audit Log For Users Activities
      • Audit Log for Admin API and Portal
      • Analytics
    • User Management
      • Account Deletion
      • Import Users using User Import API
      • Export Users using the User Export API
      • Manage Users Roles and Groups
      • How to Handle Password While Creating Accounts for Users
    • User Profiles
      • What is User Profile
      • Access User Profiles
      • Update User Profiles
      • Profile Custom Attributes
      • Update user profile on sign-up using Hooks
    • Events and Hooks
      • Event List
      • Webhooks
      • JavaScript / TypeScript Hooks
      • Only Allow Signups from Inside the Corporate Network using Hooks
    • Mobile Apps
      • Use SDK to make authorized API calls to backend
      • Force authentication on app launch
      • Customize the Login Pop-up / Disable the login alert box
    • Languages and Localization
    • Custom Email and SMS Templates
    • Directly accessing Authgear Endpoint
    • Migration
      • Bulk migration
      • Rolling migration
      • Zero-downtime migration
    • Troubleshoot
      • How to Fix SubtleCrypto: digest() undefined Error in Authgear SDK
      • How to Fix CORS Error
  • Concepts
    • Identity Fundamentals
    • Authgear use cases
    • User, Identity and Authenticator
  • Security
    • Brute-force Protection
    • Bot Protection
    • Non-HTTP scheme redirect URI
    • Password Strength
  • Reference
    • APIs
      • Admin API
        • Authentication and Security
        • API Schema
        • Admin API Examples
        • Using global node IDs
        • Retrieving users using Admin API
        • User Management Examples
          • Search for users
          • Update user's standard attributes
          • Update user's picture
          • Generate OTP code
      • Authentication Flow API
      • OAuth 2.0 and OpenID Connect (OIDC)
        • UserInfo
        • Supported Scopes
      • User Import API
      • User Export API
    • Tokens
      • JWT Access Token
      • Refresh Token
    • Glossary
    • Billing FAQ
    • Rate Limits
      • Account Lockout
  • Client App SDKs
    • Javascript SDK Reference
    • iOS SDK Reference
    • Android SDK Reference
    • Flutter SDK Reference
    • Xamarin SDK Reference
  • Deploy on your Cloud
    • Running locally with Docker
    • Deploy with Helm chart
    • Authenticating HTTP request with Nginx
    • Configurations
      • Environment Variables
      • authgear.yaml
      • authgear.secrets.yaml
    • Reference Architecture Diagrams
      • Google Cloud Reference Architecture
      • Azure Reference Architecture
      • AWS Reference Architecture
      • Throughput Scaling Reference
Powered by GitBook
On this page
  • Setup Application in Authgear
  • Step 1: Create an application in the Portal
  • Step 2: Configure the application
  • Add Authgear to your iOS Application
  • Pre-requisites
  • Step 1: Create new iOS project
  • Step 2: Install Authgear SDK
  • Step 3: Initialize Authgear SDK
  • Step 4: Add Login Button
  • Step 5: Start Authentication Flow
  • Step 6: Register URI Schema for Redirect URI
  • Step 7: Implement Logout method
  • Step 8: Show the user information
  • Step 9: Open User Settings page
  • Get the Logged In State
  • Using the Access Token in HTTP Requests
  • Next steps
  • iOS SDK Reference

Was this helpful?

Edit on GitHub
  1. Get Started
  2. Native/Mobile App

iOS SDK

Integrate your iOS application with Authgear iOS SDK

PreviousNative/Mobile AppNextAndroid SDK

Last updated 3 months ago

Was this helpful?

This guide provides instructions on integrating Authgear with an iOS app. Supported platforms include:

  • iOS 11.0 or higher

Follow this guide to add Authgear to your iOS app in 🕐 10 minutes.

You can find the full code for the demo app for this tutorial in

Setup Application in Authgear

Sign up for an Authgear Portal account at . Or you can use your self-deployed Authgear.

From the Project listing, create a new Project or select an existing Project. After that, we will need to create an Authgear client application in the project.

Step 1: Create an application in the Portal

Go to Applications on the left menu bar.

Click ⊕Add Application in the top toolbar.

Input the name of your application and select Native App as the application type. Click "Save".

You will see a list of guides that can help you for setting up, then click "Next".

Step 2: Configure the application

Head back to Authgear Portal, and add com.example.authgeardemo://host/path as Redirect URI.

Click "Save" button and note the Client ID. and Endpoint for your new client application as you'll use them later in your iOS application. You can also obtain the Client ID again from the Applications list later.

Add Authgear to your iOS Application

In this step, we'll add user authentication to a simple iOS app using the Authgear iOS SDK and the client application we created in the previous steps.

Pre-requisites

To follow the steps in this guide seamlessly, you should have the following:

  • Some knowledge of SwiftUI

Step 1: Create new iOS project

For the purpose of this guide, we'll create a new project in Xcode. Skip this step if you're adding Authgear to your existing app.

To create a new project, open Xcode and navigate to File > New > Project. Create your new project with the following details:

  • Project Name: my_demo_app

  • choose SwiftUI as Interface Leave other fields unchanged and proceed to create the project.

Step 2: Install Authgear SDK

The Authgear iOS SDK makes it easy to interact with Authgear services from your iOS project.

To add Authgear SDK to your project, in Xcode navigate to File > Add Package Dependencies and enter https://github.com/authgear/authgear-sdk-ios.git in the Package URL text field.

Click Add Package to proceed.

On the next screen, select your application under Add to Target then click on Add Package.

Alternatively, if your project uses cocoapods, install the SDK using:

pod 'Authgear', :git => 'https://github.com/authgear/authgear-sdk-ios.git'

Step 3: Initialize Authgear SDK

In this step, we'll initialize an instance of the Authgear SDK when the user interface of our app loads.

In a production app, you may want to initialize Authgear at the entry point of your app. E.g. For SwiftUI projects, this is usually a file with a name like YourProjectNameApp.swift or AppDelegate for storyboard projects.

For our demo app, add the following code to ContentView.swift

  1. First import Authgear iOS SDK:

import Authgear
  1. In struct ContentView: View {}, initialize an instance of Authgear() and call the .configure() method in an .onAppear() modifier attached to VStack like this:

private var authgear: Authgear = Authgear(clientId: "<ClIENT_ID>", endpoint: "<AUTHGEAR_ENDPOINT>")
var body: some View {
    VStack {
        Image(systemName: "globe")
            .imageScale(.large)
            .foregroundStyle(.tint)
        Text("My Demo App")
    }
    .padding()
    .onAppear() {
        authgear.configure() { result in
            switch result {
            case .success():
                // configured successfully
                print("// configured successfully")
            case let .failure(error):
                // failed to configured
                print("config failed", error)
            }
        }
    }
}

Step 4: Add Login Button

Now let's add the Login button and other UI elements for the demo app.

Add the following views to VStack:

VStack {
    if isLoading {
        ProgressView()
    }
    if loginState == SessionState.authenticated {
        Text("Welcome user \(userId ?? "user")")
        Button(action: openUserSettings) {
            Text("User Settings")
        }
        Button(action: logout) {
            Text("Logout")
        }
    } else {
        Image(systemName: "globe")
            .imageScale(.large)
            .foregroundStyle(.tint)
        Text("My Demo App")
        Button(action: startAuthentication) {
            Text("Login")
        }
    }
}

In addition to the Login button, we've included a ProgressView and a block with views we want only logged-in users to see. Create the isLoading , userId and loginState variables that the if-statement and Text view depend on at the top of the class just after private var authgear: Authgear = Authgear(...):

@State private var loginState: SessionState = .unknown
@State private var isLoading: Bool = false
@State private var userId: String? = ""

Step 5: Start Authentication Flow

Implement a startAuthentication() method in your ContentView class that will call the authenticate() method of the Authgear SDK:

func startAuthentication() {
    isLoading = true
    authgear.authenticate(redirectURI: "com.example.authgeardemo://host/path", handler: { result in
        switch result {
        case let .success(userInfo):
            // login successfully
            loginState = authgear.sessionState
            userId = userInfo.sub
            isLoading = false
        case let .failure(error):
            if let authgearError = error as? AuthgearError, case .cancel = authgearError {
                // user cancel
                isLoading = false
            } else {
                // Something went wrong
                isLoading = false
            }
        }
    })
}

In order to get your app to build at this point, add empty declarations for logout and openUserSettings methods:

func logout() {
}
    
func openUserSettings() {
}

The full code for ContentView.swift at this point should look like this:

//  ContentView.swift

import SwiftUI
import Authgear
struct ContentView: View {
    
    private var authgear: Authgear = Authgear(clientId: "<ClIENT_ID>", endpoint: "<AUTHGEAR_ENDPOINT>")
    @State private var loginState: SessionState = .unknown
    @State private var isLoading: Bool = false
    @State private var userId: String? = ""
    
    var body: some View {
        VStack {
            if isLoading {
                ProgressView()
            }
            if loginState == SessionState.authenticated {
                Text("Welcome user \(userId ?? "user")")
                Button(action: openUserSettings) {
                    Text("User Settings")
                }
                Button(action: logout) {
                    Text("Logout")
                }
            } else {
                Image(systemName: "globe")
                    .imageScale(.large)
                    .foregroundStyle(.tint)
                Text("My Demo App")
                Button(action: startAuthentication) {
                    Text("Login")
                }
            }
        }
        .padding()
        .onAppear() {
            authgear.configure() { result in
                switch result {
                case .success():
                    // configured successfully
                    print("// configured successfully")
                case let .failure(error):
                    // failed to configured
                    print("config failed", error)
                }
            }
        }
    }
    
    func startAuthentication() {
        isLoading = true
        authgear.authenticate(redirectURI: "com.example.authgeardemo://host/path", handler: { result in
            switch result {
            case let .success(userInfo):
                // login successfully
                userId = userInfo.sub
                loginState = authgear.sessionState
                isLoading = false
            case let .failure(error):
                if let authgearError = error as? AuthgearError, case .cancel = authgearError {
                    // user cancel
                    isLoading = false
                } else {
                    // Something went wrong
                    isLoading = false
                }
            }
        })
    }
    
    func logout() {
    }
    
    func openUserSettings() {
    }
}

#Preview {
    ContentView()
}

Checkpoint

Run your app now. When you click on the Login button, you should be redirected to the user authentication page.

Step 6: Register URI Schema for Redirect URI

Open your project's Info.plist or project settings UI in Xcode and add the following:

Navigate to Targets > {Your project} > Info and expand the URL Types section.

Add a new URL scheme with the following details:

Identifier: CFBundleURLTypes

URL Schemes: com.example.authgeardemo://host/path

Role: Editor

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
    <dict>
        <!-- Other entries -->
        <key>CFBundleURLTypes</key>
        <array>
            <dict>
                <key>CFBundleTypeRole</key>
                <string>Editor</string>
                <key>CFBundleURLSchemes</key>
                <array>
                    <string>com.example.authgeardemo://host/path</string>
                </array>
            </dict>
        </array>
    </dict>
</plist>

Now run your app again and try logging in. Because we've set up a redirect URL, Authgear should redirect back to our app correctly.

Step 7: Implement Logout method

Implement the logout method that will be executed when the Logout button is clicked by updating the empty logout function we added in the previous step:

func logout() {
    isLoading = true
    authgear.logout { result in
        switch result {
            case .success():
                // logout successfully
                isLoading = false
            loginState = authgear.sessionState
            case let .failure(error):
                print("failed to logout", error)
                isLoading = false// failed to login
        }
    }
}

Now clicking on the Logout button will call Authgear SDK's logout method and end the current user session.

Step 8: Show the user information

The Authgear SDK can return the current user's details via the UserInfo object. The authenticate method returns this userInfo object as demonstrated earlier in our app's startAuthentication() method. You can also call the SDK's .fetchUserInfo() method to get the UserInfo object.

Add a new getCurrentUser() method to your ContentView class:

func getCurrentUser() {
    isLoading = true
    authgear.fetchUserInfo { userInfoResult in
        // sessionState is now up to date
        // it will change to .noSession if the session is invalid
        loginState = authgear.sessionState
        
        switch userInfoResult {
        case let .success(userInfo):
            // read the userInfo if needed
            userId = userInfo.sub
            isLoading = false
        case let .failure(error):
            // failed to fetch user info
            // the refresh token maybe expired or revoked
            print("the refresh token maybe expired or revoked", error)
            isLoading = false
        }
    
    }
}

Now call the new getCurrentUser() method in the .onAppear() modifier of the VStack like this:

.onAppear() {
    authgear.configure() { result in
        switch result {
        case .success():
            // configured successfully
            // refresh access token if user has an existing session
            if authgear.sessionState == SessionState.authenticated {
                getCurrentUser()
            }
        case let .failure(error):
            // failed to configured
            print("config failed", error)
        }
    }
}

Step 9: Open User Settings page

Authgear offers a pre-built User Settings page that user's can use to view, and modify their profile attributes and security settings.

Implement the empty openUserSettings() method we added in the previous step to call the .open() method of the Authgear SDK:

func openUserSettings() {
    authgear.open(page: SettingsPage.settings)
}

Get the Logged In State

When you start launching the application. You may want to know if the user has logged in. (e.g. Show users a Login button if they haven't logged in).

The value of sessionState can be .unknown, .noSession or .authenticated. Initially, the sessionState is .unknown. After a call to authgear.configure, the session state would become .authenticated if a previous session was found, or .noSession if such session was not found.

Using the Access Token in HTTP Requests

Call refreshAccessTokenIfNeeded every time before using the access token, the function will check and make the network call only if the access token has expired. Include the access token in the Authorization header of your application request.

authgear.refreshAccessTokenIfNeeded() { result in
    switch result {
    case .success():
        // access token is ready to use
        // accessToken can be empty
        // it will be empty if user is not logged in or session is invalid

        // include Authorization header in your application request
        if let accessToken = authgear.accessToken {
            // example only, you can use your own networking library
            var urlRequest = URLRequest(url: "YOUR_SERVER_URL")
            urlRequest.setValue(
                "Bearer \(accessToken)", forHTTPHeaderField: "authorization")
            // ... continue making your request
        } else {
            // The user is not logged in, or the token is expired.
        }
    case let .failure(error):
        // Something went wrong
    }
}

Next steps

To protect your application server from unauthorized access. You will need to integrate your backend with Authgear.

iOS SDK Reference

Here you'll need to define a custom URI scheme that Authgear will use to redirect users back to your app after authentication. For our example app, this URL Scheme will be com.example.authgeardemo://host/path. For further instructions on setting up a custom URI scheme in iOS, see the official documentation .

(Latest Version)

Replace "<CLIENT_ID>" and "<AUTHGEAR_ENDPOINT>" with the client ID and endpoint from the configuration page of the client project you .

In some cases, you may need to obtain current user info through the SDK. (e.g. Display email address in the UI). Use the fetchUserInfo function to obtain the user info, see .

This will make your app refresh the access token and greet users who are already logged in with their sub (a unique user ID) when the launch the app. You can read other user attributes like email address, phone number, full name, etc. from .

The sessionState reflects the user logged-in state in the SDK local state. That means even if the sessionState is .authenticated, the session may be invalid if it is revoked remotely. Hence, after initializing the Authgear SDK, call fetchUserInfo to update the sessionState as soon as it is proper to do so. We demonstrated how to use sessionState, and fetchUserInfo, to get a user's true logged-in state and retrieve their UserInfo in .

For detailed documentation on the iOS SDK, visit .

here
Xcode
userInfo
Backend/API Integration
iOS SDK Reference
created earlier
Step 8
this Github repo
https://portal.authgear.com/
example
Create an application
Fill in the Authorized Redirect URI
Xcode new project
Xcode package manager
xcode add package
xcode project properties