Skip to contentSkip to navigationSkip to topbar
Rate this page:
On this page

Verify Push iOS Client Library Quickstart


Twilio Verify Push Client Library (SDK) helps you verify users by adding a low-friction, secure, cost-effective, push verification or device approval factor into your own mobile application. It works by registering your user's iOS devices as a secure key via public-key cryptography. When your app backend needs to verify that the user is who they say they are, you challenge the user to prove that they still possess their secure key (iOS device). This still works even if the user has disabled push notifications (APNs), as your mobile app can poll for challenges via the SDK.

You can also perform Silent Device Approval authentications from the Client Library, which are invisible to the end-user and don't require push notifications. See the How to Implement Silent Device Approval section for more information on implementing this strategy.

You can run the Verify Push iOS Client Library in your existing iOS app and verify a user using Verify Push API. This Quickstart will walk you through the entire process step-by-step, starting with setting up your Twilio account all the way through verifying a user using your existing iOS app and backend.

In this Quickstart, you will learn how to:

  1. Sign up for Twilio
  2. Configure Push Credential and Verify Service
  3. Embed the client SDK into your iOS app
  4. Setup your app backend
  5. Register a user and their device in Verify Push
  6. Configure webhooks
  7. Verify a user

By the end of this Quickstart, you'll have a solid foundation for implementing Verify Push or Silent Device Approval within your app and backend to verify users at login, transaction, and other sensitive actions.

Want a technical overview first?

Check out the Verify Push SDK Technical Overview to view its data model, sequence diagrams, and security FAQs.

Technical Overview
Want to see an example?

If you don't want to setup Verify Push with your own app or backend immediately, we have built a Sample App(link takes you to an external page) embedded with the client Verify Push iOS SDK and a Sample Backend using Twilio functions(link takes you to an external page) that you can run to see Verify Push in action. These samples can also be helpful for troubleshooting.

Want to start with Android?

Add Verify Push to your Android app with the Android SDK quickstart.


Sign up for - or sign in to - Twilio

sign-up-for---or-sign-in-to---twilio page anchor
(information)

Info

Already have a Twilio account? Go ahead and skip this section.

You can sign up for a free Twilio trial account here(link takes you to an external page).

  • When you sign up, you'll be asked to verify your personal phone number. This helps Twilio verify your identity.
  • Once you verify your number, you'll be asked to create a project. For the sake of this tutorial, you can click on the "Learn and Explore" template. Give your project a name, or just click "skip remaining steps" to continue with the default.
  • Once you get through the project creation flow, you'll arrive at your project dashboard in the Twilio Console(link takes you to an external page) . This is where you'll be able to access your Account SID, an authentication token, create a Push Credential, create a Verify Service and more.
(information)

Info


Verify Push and Push Notification

verify-push-and-push-notification page anchor

An understandable misconception is that Verify Push requires sending FCM/APNs push notifications to work. This isn't the case, because its critical flows will still work without relying on push notifications that may not be successfully delivered 100% of the time, due to issues like users turning it off, poor connectivity, OEM device manufacturer restrictions, and other factors that cut off the device from the notification service.

However, the user experience of Verify Push can be greatly improved by sending a push notification to your user's device to prompt them on the lock screen to open up your mobile app to view and approve/deny the verification request (challenge). Therefore, we recommend setting up push notifications and the next section explains how.


Set up APNs for your iOS app (optional)

set-up-apns-for-your-ios-app-optional page anchor
(information)

Info

Already configured push notifications for your iOS app? Go ahead and skip this section.

To configure push notifications, follow these Apple Push Notification service (APNs) setup steps.

Step 1 - Setup an App ID

step-1---setup-an-app-id page anchor

Log into your Apple development account(link takes you to an external page) and click on Identifiers(link takes you to an external page) under the Certificates, IDs & Profiles. This will show a list of identifiers, including App IDs.

Option 1- Existing App ID

option-1--existing-app-id page anchor

If your App ID is already on this list, click on it and a list of capabilities will be shown.

  1. Check the 'Push Notifications' capability.
  2. Don't worry about the Configure button right now, just click the Save button in the upper right.

If your App ID isn't on this list, click the "+" symbol to add a new App ID.

  1. Choose App IDs and click the Continue button in the upper right.
  2. Select App as type
  3. Give your app a description as you see fit.
  4. Give it an Explicit Bundle ID that matches the bundle identifier in Xcode (such as com.twilio.TwilioVerifyDemo).
  5. Under Capabilities check Push Notifications
  6. Click the Continue button
  7. Click the Register button to confirm your new App ID and create it.

Be sure to add Push notifications(link takes you to an external page) and Remote notifications capabilities to your Xcode project

Step 2 - Create a Certificate

step-2---create-a-certificate page anchor

Now you will need to create a push notification certificate. This will enable your app to receive notifications. You can either make a development certificate or a production certificate. For this guide, we'll make a development certificate.

  1. Add a certificate(link takes you to an external page) on the Apple Developer Portal
  2. Under Services, select 'Apple Push Notification service SSL (Sandbox)'.
  3. Click 'Continue'
  4. Select the App ID you previously created.
  5. Click 'Continue' again
  6. It will prompt you to create a Certificate Signing Request, with instructions on how to do it in the 'Learn more' link. Create one.
  7. Upload the Certificate Signing Request.
  8. Click 'Continue' again
  9. Click 'Download' to obtain your certificate.

Congrats! You just created an Apple Development iOS Push Services certificate. Now you can download it and double click on it locally to add it to your Keychain access.

(information)

Info

When creating a certificate for push notifications, you can use 'Apple Push Notification service SSL (Sandbox & Production)' if you want to use only one certificate for both environments. The certificate will be labeled as "Apple Push Services".


Create a Push Credential

create-a-push-credential page anchor

For Verify Push to send push notifications to your iOS app, you will need to create an Apple Push Notification (APN) Push Credential that contains your APN certificate and private key.

Get your certificate and private key

get-your-certificate-and-private-key page anchor

In Keychain Access, go to the 'Certificates' Category in the lefthand sidebar.

  1. Right-click your push certificate. It should be labeled "Apple Development iOS Push Services" (or "Apple Push Services").
  2. Choose "Export"
  3. Save it as cred.p12. (Leave the password blank)

This is your credential file. We're going to extract your certificate key and private key from this file. We need these 2 keys to create a Twilio Credential.

Create a Certificate Key

create-a-certificate-key page anchor

Run the following command in terminal


_10
openssl pkcs12 -in cred.p12 -nokeys -out cert.pem -nodes

Run the following command in terminal


_10
openssl pkcs12 -in cred.p12 -nocerts -out key.pem -nodes

Run the following command in terminal


_10
openssl rsa -in key.pem -out key.pem

Then you can use the certificate in the cert.pem file and the private key in the key.pem file to create a push credential

Create the push credential

create-the-push-credential page anchor

Follow these steps to do it in the Twilio Console.

  • Go to Twilio Console > Account > Keys & Credentials > Credentials > Push Credentials:
Create credential in Console.
  • Click the "Create new Credential" button to add a new credential and a form will pop-up:
2020-10-02 at 11.37.14 AM.
  • Enter a friendly name, such as "Verify Quickstart App Credentials"
  • Select APN push credentials as type
  • Enter the Certificate from the cert.pem

    • strip anything outside of "-----BEGIN CERTIFICATE-----" and "-----END CERTIFICATE-----" boundaries.
  • Enter the Private key from the key.pem.

    • strip anything outside of "-----BEGIN RSA PRIVATE KEY-----" and "-----END RSA PRIVATE KEY-----" boundaries
  • Check the Sandbox option

    • Your app should be signed with a development certificate to use sandbox
  • Click the Create button
  • Note: Although Verify Push uses Twilio Notify for sending push notifications, you do not need to create your own Notify Service
(warning)

Warning

You will need to create/update your push credential for production use, using the certificate and private key for an 'Apple Push Notification service SSL (Sandbox & Production)' certificate(link takes you to an external page) and the Sandbox checkbox should be unchecked. Your app should be signed with a production certificate.

(warning)

Warning

Certificates for push are valid for a year and must be updated to continue communicating with APNs. To avoid a disruption when sending push notifications for your users, update your certificate before they expire by creating a new one and updating the push credential.


Create a Verify Service and add the Push Credential

create-a-verify-service-and-add-the-push-credential page anchor

Embed the SDK into your iOS app

embed-the-sdk-into-your-ios-app page anchor

Follow the installation steps in the README file of the Twilio Verify iOS repo(link takes you to an external page). The installation steps will explain how to add the iOS library to your project and setup your iOS app to work with Apple Push Notification service (APNs).

After you import the Twilio Verify iOS library, you can start to integrate your existing app with Verify Push.

To get started, you will need to create an instance of the TwilioVerify class, using its Builder. Do this by typing or pasting in the code sample.

Embed the SDK into your app

embed-the-sdk-into-your-app page anchor

_10
do {
_10
let twilioVerify = try TwilioVerifyBuilder().build()
_10
} catch {
_10
// Handle error
_10
}

(warning)

Warning

The SDK should be used from a Swift class.

Full source(link takes you to an external page)


Obtain a Verify Push API access token for your iOS app

obtain-a-verify-push-api-access-token-for-your-ios-app page anchor

Your iOS app needs to obtain an Access Token (technically an Enrollment JWE, similar to a JSON Web Token (JWT)) to make direct requests to the Verify Push API in the future. This Access Token request needs to be brokered by your app backend. To do this, you need to:

  1. Expose an API endpoint in your app backend for your iOS app to request the Access Token
  2. Have your app backend request an Access Token from Verify Push API
  3. Return the Access Token, identity and Verify Service SID to the iOS app

Expose an API endpoint in your app backend for your app to request the Access Token

expose-an-api-endpoint-in-your-app-backend-for-your-app-to-request-the-access-token page anchor

Check out our Sample Backend using Twilio functions(link takes you to an external page) for an implementation example. In a production web application, you would restrict access token retrieval to the currently authenticated user, using whatever type of authentication your service already uses.

Have your app backend request an Access Token from Verify Push API

have-your-app-backend-request-an-access-token-from-verify-push-api page anchor

In the sidebar to the right (or below) is sample code for requesting an access token from the Verify Push API in all languages supported by Twilio helper libraries. You will need the Verify service_sid, as well as the user id (such as a GUID or the user's primary key in your database table) you use as the identity with this Verify service.

Request an Access Token from Verify Push API

request-an-access-token-from-verify-push-api page anchor

Your app backend should make this request

Node.js
Python
C#
Java
Go
PHP
Ruby
twilio-cli
curl

_11
// Download the helper library from https://www.twilio.com/docs/node/install
_11
// Find your Account SID and Auth Token at twilio.com/console
_11
// and set the environment variables. See http://twil.io/secure
_11
const accountSid = process.env.TWILIO_ACCOUNT_SID;
_11
const authToken = process.env.TWILIO_AUTH_TOKEN;
_11
const client = require('twilio')(accountSid, authToken);
_11
_11
client.verify.v2.services('VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
_11
.accessTokens
_11
.create({identity: 'User_UUID', factorType: 'push'})
_11
.then(access_token => console.log(access_token.sid));

Output

_12
{
_12
"sid": "YKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
_12
"account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
_12
"service_sid": "VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
_12
"entity_identity": "ff483d1ff591898a9942916050d2ca3f",
_12
"factor_type": "push",
_12
"factor_friendly_name": "John Doe iPhone",
_12
"ttl": 300,
_12
"date_created": "2015-07-30T20:00:00Z",
_12
"token": "eyJ6aXAiOiJERUYiLCJraWQiOiJTQVNfUzNfX19LTVNfdjEiLCJjdHkiOiJ0d2lsaW8tZnBhO3Y9MSIsImVuYyI6IkEyNTZHQ00iLCJhbGciOiJkaXIifQ..qjltWfIgQaTwp2De.81Z_6W4kR-hdlAUvJQCbwS8CQ7QAoFRkOvNMoySEj8zEB4BAY3MXhPARfaK4Lnr4YceA2cXEmrzPKQ7bPm0XZMGYm1fqLYzAR8YAqUetI9WEdQLFytg1h4XnJnXhgd99eNXsLkpKHhsCnFkchV9eGpRrdrfB0STR5Xq0fdakomb98iuIFt1XtP0_iqxvxQZKe1O4035XhK_ELVwQBz_qdI77XRZBFM0REAzlnEOe61nOcQxkaIM9Qel9L7RPhcndcCPFAyYjxo6Ri5c4vOnszLDiHmeK9Ep9fRE5-Oz0px0ZEg_FgTUEPFPo2OHQj076H1plJnFr-qPINDJkUL_i7loqG1IlapOi1JSlflPH-Ebj4hhpBdMIcs-OX7jhqzmVqkIKWkpPyPEmfvY2-eA5Zpoo08YpqAJ3G1l_xEcHl28Ijkefj1mdb6E8POx41skAwXCpdfIbzWzV_VjFpmwhacS3JZNt9C4hVG4Yp-RGPEl1C7aJHRIUavAmoRHaXbfG20zzv5Zu0P5PcopDszzoqVfZpzc.GCt35DWTurtP-QaIL5aBSQ",
_12
"url": "https://verify.twilio.com/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/AccessTokens/YKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
_12
}

(warning)

Warning

Do not use Personally Identifiable Information for identity. Use an immutable user identifier like a UUID, GUID, or SID.
Verify Push uses identity as a unique identifier of a user. You should not use directly identifying information (aka personally identifiable information or PII) like a person's name, home address, email or phone number, etc., as identity because the systems that will process this attribute assume it is not directly identifying information.


Register a user and their device

register-a-user-and-their-device page anchor
(warning)

Warning

Do not store your Verify Service SID in your app. Get it from your backend, as well as the identity. You can find an example in the Sample Backend using Twilio functions(link takes you to an external page)

Register a user and their device in Verify Push by creating and verifying a Factor. Type or paste the code samples for both of these steps.

(information)

Info

You don't need to make a separate Create Entity call, because the Create Factor call will create an Entity and a Factor at the same time.

(information)

Info

You can add custom metadata associated with the factor on creation. This is added by the Device/SDK directly to allow for the inclusion of device information. Available in SDK version 2.2.0 and above.

(warning)

Warning

As getting the device token for push(link takes you to an external page) could happen in a different moment before creating the factor, please validate that your app has a device token before using it as a pushToken in the create factor method. You will need to pass the device token as a hexadecimal string representation, check the implementation(link takes you to an external page). If you don't want to configure push notification for this factor, then set the pushToken to nil.


_13
let payload = PushFactorPayload(
_13
friendlyName: factorName,
_13
serviceSid: verifyServiceSid,
_13
identity: identity,
_13
pushToken: pushToken,
_13
accessToken: accessToken,
_13
metadata: ["os": "iOS"] // Custom metadata associated with the factor. Optional
_13
)
_13
twilioVerify.createFactor(withPayload: payload, success: { factor in
_13
// Success
_13
}) { error in
_13
// Error
_13
}

Full source(link takes you to an external page)


_10
let payload = VerifyPushFactorPayload(sid: factorSid)
_10
twilioVerify.verifyFactor(withPayload: payload, success: { factor in
_10
// Success
_10
}) { error in
_10
// Error
_10
}

Full source(link takes you to an external page)

(information)

Info

  • By default, the created factors and key pairs will not persist in the device after the app is uninstalled and reinstalled for security reasons. However, it's possible to change this default behavior and persist the factors and key pairs after a reinstall, because both are saved in the keychain. Check this(link takes you to an external page) to know how to do it.
  • The Verify API has a limit of 20 Factors of factor_type=push per Entity. This limit could be reached if a user uninstalls and reinstalls your app frequently. Unverified Factors will be automatically deleted and unverifiable after 1-24 hours from when they were created, but you will need to explicitly delete verified Factors .

Configure webhooks (optional)

configure-webhooks-optional page anchor

Configure a webhook callback for your app backend to be notified of events such as when a Factor has been verified or when a Challenge has been approved, so that it knows to advance the user to the next step in your flow. This is more real-time and efficient than constantly polling the Verify Push API for the status of a Factor or Challenge.

Follow the steps in this Verify Webhooks page.

Specify events to send to your callback URL

Node.js
Python
C#
Java
Go
PHP
Ruby
twilio-cli
curl

_15
// Download the helper library from https://www.twilio.com/docs/node/install
_15
// Find your Account SID and Auth Token at twilio.com/console
_15
// and set the environment variables. See http://twil.io/secure
_15
const accountSid = process.env.TWILIO_ACCOUNT_SID;
_15
const authToken = process.env.TWILIO_AUTH_TOKEN;
_15
const client = require('twilio')(accountSid, authToken);
_15
_15
client.verify.v2.services('VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
_15
.webhooks
_15
.create({
_15
friendlyName: 'My Webhook',
_15
eventTypes: ['*'],
_15
webhookUrl: 'https://mywebsite.com/webhook'
_15
})
_15
.then(webhook => console.log(webhook.sid));

Output

_16
{
_16
"url": "https://verify.twilio.com/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Webhooks/YWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
_16
"sid": "YWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
_16
"account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
_16
"service_sid": "VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
_16
"friendly_name": "My Webhook",
_16
"event_types": [
_16
"*"
_16
],
_16
"webhook_method": "POST",
_16
"webhook_url": "https://mywebsite.com/webhook",
_16
"status": "enabled",
_16
"version": "v2",
_16
"date_created": "2015-07-30T20:00:00Z",
_16
"date_updated": "2015-07-30T20:00:00Z"
_16
}


Congratulations! Verify Push consists of two user sequences, and you've just completed the first one: user and device registration. The second sequence is to challenge and verify (authenticate) a user with their registered device. Read on for the step-by-step instructions.


Your web application backend needs to call the Verify Push API to create a Challenge using the Factor that you've just created. When the challenge is created, Verify Push sends a push notification to the registered device using the configured Push Credential.

The code in the sidebar to the right/bottom demonstrates how to create those challenges using the Twilio helper libraries.

Create a Challenge to verify a user

create-a-challenge-to-verify-a-user page anchor
Node.js
Python
C#
Java
Go
PHP
Ruby
twilio-cli
curl

_20
// Download the helper library from https://www.twilio.com/docs/node/install
_20
// Find your Account SID and Auth Token at twilio.com/console
_20
// and set the environment variables. See http://twil.io/secure
_20
const accountSid = process.env.TWILIO_ACCOUNT_SID;
_20
const authToken = process.env.TWILIO_AUTH_TOKEN;
_20
const client = require('twilio')(accountSid, authToken);
_20
_20
client.verify.v2.services('VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
_20
.entities('User_UUID')
_20
.challenges
_20
.create({
_20
'details.message': 'Message shown to the user when the push notification arrives',
_20
'details.fields': [{'label': 'msg', 'value': 'Challenge details shown to user'}],
_20
hiddenDetails: {
_20
msg: 'Challenge details not shown to user'
_20
},
_20
expirationDate: new Date(Date.UTC(2020, 6, 30, 21, 0, 0)),
_20
factorSid: 'YFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
_20
})
_20
.then(challenge => console.log(challenge.sid));

Output

_33
{
_33
"sid": "YC03aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
_33
"account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
_33
"service_sid": "VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
_33
"entity_sid": "YEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
_33
"identity": "User_UUID",
_33
"factor_sid": "YFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
_33
"date_created": "2015-07-30T20:00:00Z",
_33
"date_updated": "2015-07-30T20:00:00Z",
_33
"date_responded": "2015-07-30T20:00:00Z",
_33
"expiration_date": "2020-07-30T21:00:00Z",
_33
"status": "pending",
_33
"responded_reason": "none",
_33
"details": {
_33
"message": "Hi! Mr. John Doe, would you like to sign up?",
_33
"date": "2020-07-01T12:13:14Z",
_33
"fields": [
_33
{
_33
"label": "Action",
_33
"value": "Sign up in portal"
_33
}
_33
]
_33
},
_33
"hidden_details": {
_33
"msg": "Challenge details not shown to user"
_33
},
_33
"metadata": null,
_33
"factor_type": "push",
_33
"url": "https://verify.twilio.com/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Entities/ff483d1ff591898a9942916050d2ca3f/Challenges/YC03aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
_33
"links": {
_33
"notifications": "https://verify.twilio.com/v2/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Entities/ff483d1ff591898a9942916050d2ca3f/Challenges/YC03aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Notifications"
_33
}
_33
}

(information)

Info

  • You may choose to put Personally Identifiable Information (PII) or other sensitive information in details and hidden_details . The data in each param will be stored per its retention policy listed in the Challenge resource.
  • If you are sending push notifications, use the Notifications resource to resend a push notification if the first one fails for some reason . This is better than creating another duplicate Challenge.

Now that the pending Challenge has been created in the Verify API, your mobile app needs to become aware of it. This can be done by telling your user to open up your mobile app on the registered device, and then having your app check (poll) the Verify API for any pending Challenges whenever it's opened.

Example implementation

  1. Display a message for your user to open your app on the registered device: "Approve this login/transaction by opening the [App name] app and tapping [Approve button text]
  2. Know when the app is opened and in foreground, then automatically poll for pending challenges.

    1. Android: Use the onResume()(link takes you to an external page) method of your activity or subscribe to a lifecycle observer.(link takes you to an external page)
    2. iOS: Use the applicationWillEnterForeground(link takes you to an external page) method in your application delegate or sceneWillEnterForeground(link takes you to an external page) if your app supports scenes, see more info here.(link takes you to an external page)
  3. Alternatively, you can display to the user an "inbox" menu item to manually check for "pending verification requests" (challenges)
  4. To get the pending challenges you can call the getAllChallenges method in the SDK, passing Pending as ChallengeListPayload's status and Desc as ChallengeListPayload's order
  5. You can define the number of challenges to be returned using ChallengeListPayload's pageSize. To show only one challenge, pass 1 as ChallengeListPayload's pageSize
  6. You can display the pending challenge(s) as a pop-up, just like if your app had received a push notification
  7. Alternatively, you can show multiple pending challenges in an "inbox" menu item. You can display a badge number in the inbox to let the user know how many pending challenges are waiting for them.
(warning)

Warning

Make sure to specify Desc as the ChallengeListPayload's order in step 4 above and whenever you want to get the most recent challenge first. If you don't specify Desc, the list will default to returning Asc order (oldest challenge first), which could create high latency and a timeout error if the list of challenges is long and you are looking for the most recent challenge.


_10
let payload = ChallengeListPayload(factorSid: factorSid, pageSize: defaultPageSize, status: .pending, order: .desc)
_10
twilioVerify.getAllChallenges(withPayload: payload, success: { [weak self] list in
_10
guard let strongSelf = self else { return }
_10
// Show pending challenge(s)
_10
}) { [weak self] error in
_10
// Error
_10
}


Read Push Notification (optional)

read-push-notification-optional page anchor

Your iOS app needs to read the contents of the push notification payload(link takes you to an external page) to obtain the challengeSid, factorSid, and message parameters.

Typically, you would do this either directly in the AppDelegate class, or you would create a new class that handled incoming push notifications that you reference in your AppDelegate class.

The following code sample runs when there is an incoming push notification, and if the type is verify_push_challenge, reads the parameters out of the notification.

(warning)

Warning

Because the user might consider notification-based interactions disruptive, you must obtain permission(link takes you to an external page) to use them.


_39
// Background
_39
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
_39
defer { completionHandler() }
_39
_39
guard response.actionIdentifier == UNNotificationDefaultActionIdentifier else {
_39
return
_39
}
_39
guard let data = response.notification.request.content.userInfo as? [AnyHashable: Any] else {
_39
return
_39
}
_39
guard let challengeSid = data["challenge_sid"] as? String,
_39
let factorSid = data["factor_sid"] as? String,
_39
let type = data["type"] as? String, type == "verify_push_challenge" else {
_39
return
_39
}
_39
_39
// Show push notification or update challenge
_39
}
_39
_39
// Foreground
_39
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
_39
guard response.actionIdentifier == UNNotificationDefaultActionIdentifier else {
_39
completionHandler(UNNotificationPresentationOptions(rawValue: 0))
_39
return
_39
}
_39
guard let data = response.notification.request.content.userInfo as? [AnyHashable: Any] else {
_39
completionHandler(UNNotificationPresentationOptions(rawValue: 0))
_39
return
_39
}
_39
guard let challengeSid = data["challenge_sid"] as? String,
_39
let factorSid = data["factor_sid"] as? String,
_39
let type = data["type"] as? String, type == "verify_push_challenge" else {
_39
completionHandler(UNNotificationPresentationOptions(rawValue: 0))
_39
return
_39
}
_39
_39
// Show push notification or update challenge
_39
completionHandler(.sound)
_39
}

Testing push notifications on simulators

testing-push-notifications-on-simulators page anchor

You can test push notifications on simulators. The Xcode command-line tools allow you to send push notifications from the terminal, this command allows you to send a push notification to the iOS simulator:


_15
xcrun simctl push --help
_15
Send a simulated push notification
_15
Usage: simctl push <device> [<bundle identifier>] (<json file> | -)
_15
_15
bundle identifier
_15
The bundle identifier of the target application
_15
If the payload file contains a 'Simulator Target Bundle' top-level key this parameter may be omitted.
_15
If both are provided this argument will override the value from the payload.
_15
json file
_15
Path to a JSON payload or '-' to read from stdin. The payload must:
_15
- Contain an object at the top level.
_15
- Contain an 'aps' key with valid Apple Push Notification values.
_15
- Be 4096 bytes or less.
_15
_15
Only application remote push notifications are supported. VoIP, Complication, File Provider, and other types are not supported.

The command requires the arguments:

  • <device>: set this to booted to use the open simulator. You can also use a device identifier which you could get with the xcrun simctl list devices | grep Booted command.
  • <bundle identifier>: bundle identifier of the app you are testing.
  • <json file>: a JSON file containing the push notification details.

The JSON content for getting a challenge push notification is:


_10
{
_10
"aps": {
_10
"alert": "<Challenge message>",
_10
"category": "verify_push_challenge"
_10
},
_10
"message": "<Challenge message>",
_10
"challenge_sid": "<challenge_sid>",
_10
"factor_sid": "<factor_sid>",
_10
"type": "verify_push_challenge"
_10
}

  • <Challenge message> : The message for the challenge
  • <factor_sid> : A valid factor Sid, created in the device
  • <challenge_sid> : A valid challenge Sid, created for the factor

Running this command for the sample app will be:


_10
xcrun simctl push booted com.twilio.TwilioVerifyDemo payload.json

You can see an example here(link takes you to an external page)

Once your app receives the push notification containing the challengeSid, it needs to retrieve the challenge details that correspond to that sid. Type/paste the sample code below. This step is not necessary if you have already retrieved the challenge details via the getAllChallenges method as previously instructed in the "poll for the challenge" section.

Get and display Challenge details

get-and-display-challenge-details page anchor

_10
twilioVerify.getChallenge(challengeSid: challengeSid, factorSid: factorSid, success: { challenge in
_10
// Success
_10
}) { error in
_10
// Error
_10
}

Full source(link takes you to an external page)

(information)

Info

See additional tips for push notifications and ensuring that the device receives the challenge here.


Update the Challenge to verify the user

update-the-challenge-to-verify-the-user page anchor

In an actual implementation, your iOS app should either display the Challenge details to the user and request confirmation that the Challenge is expected, or silently approve the Challenge, because your app already knows that the user is trying to login on the same device as the registered device that is being challenged.

In either case, the next step is for your app to call the Verify Push API directly and update the Challenge status as approved or denied. Type or paste the sample code into your iOS app.

Update the Challenge to verify the user

update-the-challenge-to-verify-the-user-1 page anchor

_10
let payload = UpdatePushChallengePayload(
_10
factorSid: factorSid,
_10
challengeSid: challengeSid,
_10
status: newStatus
_10
)
_10
twilioVerify.updateChallenge(withPayload: payload, success: {
_10
// Success
_10
}) { error in
_10
// Error
_10
}

Full source(link takes you to an external page)

How to Implement Silent Device Approval

how-to-implement-silent-device-approval page anchor

By optionally implementing Silent Device Approval within the Verify Push Client Library, you can silently approve challenges without push notifications when your app already knows that the user is trying to complete an action (actively logging in, making a transaction, etc.) on the same device as the registered device that is being challenged. This results in an authentication that is completely invisible to the user. While implementation details will vary, here are some suggested steps:

  • In order to be confident about the user's intent, the challenge approval should be done when the app is in foreground during the flow of the action that is being approved (e.g. immediately after the user taps "login").
  • Identify the device starting the action and create a challenge for the factor linked to that device (a factor only represents one device).
  • If you want to send challenges for multiple devices (factors) or if you want to be sure that you're approving the correct challenge, there are two options:

    • Include the associated challenge sid for the action in the response to the device and validate that it's the expected challenge sid before approving it.
    • Assign a transaction id to the started action and include it in the response to the device, and add the transaction id to the challenge's hidden details, so before approving the challenge you can get the challenge's hidden details to validate it is the expected challenge
  • To receive the challenge on the client-side, you can:

    • Implement a strategy to listen for incoming push notifications when the app is in foreground and after some seconds, poll for pending challenges just in case the push notification did not arrive.
    • Poll for the latest pending challenge for an immediate approval, if your backend implementation can guarantee that the challenge was already created.

For additional suggestions, see:


Receive Challenge status

receive-challenge-status page anchor

Once Verify Push API receives a Challenge update from your iOS app, it will forward the update by sending a webhook callback (challenge.approved or challenge.denied) to your app backend, so that it knows to take your user to the next step in your flow. If you don't have a webhook configured, you can poll the Verify Push API for the status of the Challenge.

This completes the second user sequence of Verify Push: Challenge and verify a user.


Now that you've verified your first user, check out the following resources to continue your Verify Push journey with Twilio:

We can't wait to see what you build!


Rate this page: