iOS Swift: Login

View on Github

iOS Swift: Login

Gravatar for martin.walsh@auth0.com
By Martin Walsh

This tutorial demonstrates how to add user login to a Swift application using Auth0. We recommend that you log in to follow this quickstart with examples configured for your account.

I want to explore a sample app

2 minutes

Get a sample configured with your account settings or check it out on Github.

View on Github
System requirements: Cocoapods 1.9 | iOS 9+ | Xcode 12.x / 13.x

Before You Start

This tutorial demonstrates how to add user login to a Swift application using Web Authentication with Auth0. Alternatively, check out the iOS Swift - Sign In With Apple tutorial.

Configure Auth0

Get Your Application Keys

When you signed up for Auth0, a new application was created for you, or you could have created a new one. You will need some details about that application to communicate with Auth0. You can get these details from the Application Settings section in the Auth0 dashboard.

App Dashboard

You need the following information:

  • Domain
  • Client ID

Add your credentials in Auth0.plist. If the file does not exist in your project yet, create one with the information below (Apple documentation on Property List Files):

<!-- Auth0.plist -->

<?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>

Was this helpful?

/

Configure Callback URLs

A callback URL is a URL in your application where Auth0 redirects the user after they have authenticated. The callback URL for your app must be added to the Allowed Callback URLs field in your Application Settings. If this field is not set, users will be unable to log in to the application and will get an error.

In your application's Info.plist file, register your iOS Bundle identifier as a custom scheme:

<!-- Info.plist -->

<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleTypeRole</key>
        <string>None</string>
        <key>CFBundleURLName</key>
        <string>auth0</string>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
        </array>
    </dict>
</array>

Was this helpful?

/

Go to your Dashboard Settings and make sure that the Allowed Callback URLs field contains the following callback URL:

{PRODUCT_BUNDLE_IDENTIFIER}://YOUR_DOMAIN/ios/{PRODUCT_BUNDLE_IDENTIFIER}/callback

Was this helpful?

/

e.g. If your bundle identifier was com.company.myapp and your domain was company.auth0.com then this value would be

com.company.myapp://company.auth0.com/ios/com.company.myapp/callback

Was this helpful?

/

Start the Authentication

Universal Login is the easiest way to set up authentication in your application. We recommend using it for the best experience, best security and the fullest array of features.

Universal Login

Install Dependencies

Cocoapods

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

pod 'Auth0', '~> 1.0'

Was this helpful?

/

Then run pod install.

Carthage

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

github "auth0/Auth0.swift" ~> 1.0

Was this helpful?

/

Then run carthage bootstrap.

SPM

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

File > Add Packages...

In the Search or Enter Package URL search box enter this url:

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

Was this helpful?

/

Then select the dependency rule and press Add Package.

Add the Callback (iOS < 11 only)

For Auth0 to handle the authentication callback, update your AppDelegate file.

First, import the Auth0 module:

import Auth0

Was this helpful?

/

Then, add the following UIApplicationDelegate method:

// AppDelegate.swift

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

Was this helpful?

/

Implement Login

First, import the Auth0 module in the file where you want to present the login page:

import Auth0

Was this helpful?

/

Then, in the action of your Login button, add the following snippet to present the login screen:

// HomeViewController.swift

Auth0
    .webAuth()
    .scope("openid profile")
    .audience("https://YOUR_DOMAIN/userinfo")
    .start { result in
        switch result {
        case .failure(let error):
            // Handle the error
            print("Error: \(error)")
        case .success(let credentials):
            // Do something with credentials e.g.: save them.
            // Auth0 will automatically dismiss the login page
            print("Credentials: \(credentials)")
        }
}

Was this helpful?

/

This adds the profile scope to enable retrieving the User Profile.

After the user authenticates, their information is returned in a Credentials object.

Configure Logout URLs

A logout URL is a URL in your application that Auth0 can return to after the user has been logged out of the authorization server. This is specified in the returnTo query parameter. The logout URL for your app must be added to the Allowed Logout URLs field in your Application Settings. If this field is not set, users will be unable to log out from the application and will get an error.

Implement Logout

To clear the Universal Login session you need to invoke the clearSession method. Add the following snippet in the action of your Logout button:

// HomeViewController.swift

Auth0
    .webAuth()
    .clearSession(federated: false) { result in
        if result {
            // Session cleared
        }
    }

Was this helpful?

/

Go to your Dashboard Settings and make sure that the Allowed Logout URL field contains the following logout callback URL:

{PRODUCT_BUNDLE_IDENTIFIER}://YOUR_DOMAIN/ios/{PRODUCT_BUNDLE_IDENTIFIER}/callback

Was this helpful?

/

After the call, the callback will receive a BOOL with the logout status.

Use Auth0 for FREE