Auth0.swift

Auth0.swift is a client-side library for Auth0. Check out the Auth0.swift repository on GitHub.

Requirements

  • iOS 9+ / macOS 10.11+ / tvOS 9.0+ / watchOS 2.0+

  • Xcode 11.4+ / 12.x

  • Swift 4.x / 5.x

Installation

Cocoapods

If you are using Cocoapods, add this line to your Podfile:

pod 'Auth0', '~> 1.0'

Then run pod install.

For more information on Cocoapods, check their official documentation.

Carthage

If you are using Carthage, add the following line to your Cartfile:

github "auth0/Auth0.swift" ~> 1.0

Then run carthage bootstrap.

For more information about Carthage usage, check their official documentation.

SPM

If you are using the Swift Package Manager, open the following menu item in Xcode:

File > Swift Packages > Add Package Dependency...

In the Choose Package Repository prompt add this url:

https://github.com/auth0/Auth0.swift.git

Then press Next and complete the remaining steps.

For further reference on SPM, check its official documentation.

Adding Auth0 Credentials

You will need to add an Auth0.plist file, containing your Auth0 client id and domain, to your main bundle. Here is an example of the file contents:

to configure this snippet with your account

<?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>
   <key>ClientId</key>
   <string>YOUR_CLIENT_ID</string>
   <key>Domain</key>
   <string>YOUR_DOMAIN</string>
</dict>
</plist>

Web-based Auth (iOS / macOS 10.15+)

First go to Auth0 Dashboard and go to application's settings. Make sure you have in Allowed Callback URLs a URL with the following format:

{YOUR_BUNDLE_IDENTIFIER}://YOUR_DOMAIN/ios/{YOUR_BUNDLE_IDENTIFIER}/callback

In your application's Info.plist file register your iOS Bundle Identifier as a custom scheme like this:

<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleTypeRole</key>
        <string>None</string>
        <key>CFBundleURLName</key>
        <string>auth0</string>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>{YOUR_BUNDLE_IDENTIFIER}</string>
        </array>
    </dict>
</array>

If your Info.plist is not shown in this format, you can Right Click on Info.plist in Xcode and then select Open As / Source Code.

Auth0.swift will only handle URLs with your Auth0 domain as host, for example com.auth0.MyApp://samples.auth0.com/ios/com.auth0.MyApp/callback

Add the Callback (iOS < 12 only)

Skip this step if your app targets iOS 12+ (e.g. if it uses the SwiftUI app lifecycle).

Allow Auth0 to handle authentication callbacks. In your AppDelegate.swift, add the following:

iOS

func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey: Any]) -> Bool {
    return Auth0.resumeAuth(url)
}

macOS

func application(_ application: NSApplication, open urls: [URL]) {
    Auth0.resumeAuth(urls)
}

Authenticate with Universal Login

The first step in adding authentication to your application is to provide a way for your users to log in. The fastest, most secure, and most feature-rich way to do this with Auth0 is to use Universal Login.

For more information on the two types of login flows, please refer to Browser-Based vs. Native Login Flows on Mobile Devices

Auth0
    .webAuth()
    .audience("https://YOUR_DOMAIN/userinfo")
    .start { result in
        switch result { // Auth0.Result
        case .success(let credentials):
            print("Credentials: \(credentials)")
        case .failure(let error):
            print(error)
        }
    }

To ensure a response that complies with OpenID Connect (OIDC), you must either request an audience or enable the OIDC Conformant switch in your Auth0 dashboard, under Application > Settings > Show Advanced Settings > OAuth.

Authenticate with a specific Auth0 connection

The connection option allows you to specify a connection that you wish to authenticate with. If no connection is specified here, the browser will show the login page, with all of the connections which are enabled for this application.

Auth0
    .webAuth()
    .connection("facebook")
    .audience("https://YOUR_DOMAIN/userinfo")
    .start { result in
        switch result {
        case .success(let credentials):
            print("Credentials: \(credentials)")
        case .failure(let error):
            print(error)
        }
    }

Authenticate using a specific scope

Using scopes can allow you to return specific claims for specific fields in your request. Adding parameters to scope will allow you to add more scopes. The default scope is openid, and you should read our documentation on scopes for further details about them.

Auth0
    .webAuth()
    .scope("openid email")
    .connection("google-oauth2")
    .audience("https://YOUR_DOMAIN/userinfo")
    .start { result in
        switch result {
        case .success(let credentials):
            print("Credentials: \(credentials)")
        case .failure(let error):
            print(error)
        }
    }

Getting user information

In order to retrieve a user's profile, you call the userInfo method and pass it the user's accessToken. Although the call returns a UserInfo instance, this is a basic OIDC conformant profile and the only guaranteed claim is the sub, which contains the user's ID. Depending on the requested scope, the claims returned may vary. You can also use the sub value to call the Management API and return a full user profile.

Auth0
   .authentication()
   .userInfo(withAccessToken: accessToken)
   .start { result in
       switch result {
       case .success(let profile):
           print("User Profile: \(profile)")
       case .failure(let error):
           print("Failed with \(error)")
       }
   }

Learn more