CyberArk Identity SDK for Android

This topic describes how to integrate CyberArk Identity multi-factor authentication with your Android mobile app.


CyberArk Identity Android SDK provides an authentication framework that enables you to implement CyberArk's advanced Multi-factor Authentication (MFA) services within your mobile app.
Using the SDK, you can integrate a rich set of authentication factors, such as QR Code authentication and push authentication, to provide users with a seamless and secure end user experience.

Before you begin

Before you begin this tutorial, make sure you have created a CyberArk Free Trial account to view your tenant details. You need a tenant ID and tenant URL to:

  • Register your Android app in CyberArk Identity.
  • Redirect your app to CyberArk Identity with a set of authentication challenges for end users signing in using an Android app.

    The Identity Android SDK package handles all of the interactions with CyberArk Identity to provide a secure and trusted login flow.

CyberArk Identity automatically generates a tenant URL for each (tenant) account by prefixing the tenant ID to the tenant URL. For example mytenant is your tenant ID in tenant URL. To find your tenant details in the Admin Portal, navigate to Settings > Customization > Login > Tenant URLs. Refer to the following figure for an example.

The Admin Portal also lets you configure the authorization code flow for your Android app to receive an Access Token and ID token or Refresh Token.

The tenant URL that the Identity Service generates is also known as system URL. You need a system URL to redirect your Android app when a user must authenticate.

The supplied code samples in this tutorial are written in the Kotlin programming language.

Configure CyberArk as OAuth2 Identity provider

In order to utilize CyberArk Identity, you need to set up an OAuth2 Client in the Admin Portal so that your app can receive Access Token and ID token or Refresh Token from the OAuth2 Client after an authorization grant from CyberArk Identity.

For steps and instructions for creating an OAuth 2.0 Client application in the Admin Portal, refer to
Client Credentials Flow.


If you are developing a public app, such as a mobile app where the client secret is not secure, the Authorization Code Flow with PKCE is recommended. To do this, select List (Apps > Web Apps > OAuth2 Client > General Usage > List) and add Allowed Clients in the Admin Portal.

Integrate the Identity Android SDK into your project

This section explains how to include the CyberArk Identity Android SDK in your Android app so that you can call Identity APIs for a secure login flow.

Step 1: Download Identity Android SDK package

A copy of the Identity Android SDK package (.aar) file is available on GitHub. You can download a copy and manually import it into your project. Click here to start downloading Identity Android SDK.

Step 2: Import the Identity Android SDK package into your project

Manually import the downloaded SDK package into your project for integration. To import the SDK package, copy the package and paste it into Project > app > libs, as shown below.

After you import the SDK package, start Gradle sync.

Step 3: Declare Gradle Implementation dependencies

When you use Gradle to build your app for Android, you must declare the Identity SDK dependencies so that Gradle can download all the required dependencies. Add the following in your app/build.gradle.

implementation files('libs/identitylibrary-release.aar') 
implementation "androidx.preference:preference-ktx:1.1.1"
//In-build unit test framework libs
testImplementation 'androidx.test:core:1.4.0'
testImplementation "androidx.arch.core:core-testing:2.1.0"
testImplementation ""
//In-build android test framework libs
//External test framework libs
testImplementation 'org.powermock:powermock-module-junit4:2.0.9'
testImplementation 'org.powermock:powermock-module-junit4-rule:2.0.9'
testImplementation 'org.powermock:powermock-classloading-xstream:2.0.9'
testImplementation 'org.powermock:powermock-api-mockito2:2.0.9'
testImplementation 'org.robolectric:robolectric:4.6.1'
testImplementation 'net.bytebuddy:byte-buddy:1.11.15'
testImplementation "org.json:json:20210307"
testImplementation "org.mockito.kotlin:mockito-kotlin:3.2.0"
//mockito should be at 3.2.4 for java 11
testImplementation 'org.mockito:mockito-core:3.9.0'
//"powermock-classloading-xstream" lib is dependent on "com.thoughtworks.xstream" lib to handle Snyk scan issues
implementation 'com.thoughtworks.xstream:xstream:1.4.18'
//"org.robolectric:robolectric" lib is dependent on "" lib to handle Snyk scan issues
implementation ''
//LifeCycle libs
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1'
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.3.1'
//Custom tab support browser plugin
implementation "androidx.browser:browser:1.3.0"
//Biometrics support libs
implementation "androidx.biometric:biometric:1.2.0-alpha03"  
//Retrofit network libs
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.squareup.okhttp3:okhttp:5.0.0-alpha.2'
//External libs
implementation('com.journeyapps:zxing-android-embedded:4.2.0') { transitive = false }
implementation ''
implementation 'pub.devrel:easypermissions:3.0.0'

Step 4: Verify the supported SDK version

To run the Identity SDK, the minimum supported Android SDK version is API level 24 and above.

compileSdkVersion 31
buildToolsVersion "30.0.3"

defaultConfig {
    applicationId "com.cyberark.mfa"
    minSdkVersion 24
    targetSdkVersion 31
    versionCode 1
    versionName "1.0"

Step 5: Use Java 8 language features

The Identity Android SDK requires Java 8 language feature support. To enable Java 8 support for Android and Kotlin plugins respectively, add the following compile options in your build.gradle file in your app folder.

compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    kotlinOptions {
        jvmTarget = '1.8' 

Step 6: Add permission in AndroidManifest.xml

Open your app's AndroidManifest.xml file and add the following permission.

To perform actions on the token, you need to add the INTERNET permission to your AndroidManifest.xml file.

<manifest. >
<uses-permission android:name="android.permission.INTERNET" />
</manifest. >

Step 7: Read values from config.xml

Create a string (config.xml) resource file that is referenced using the value provided in the name attribute.
Create a config.xml (Identity-demo-android > res > config.xml) and add the following resources.

    <string name="cyberark_account_system_url">{YOUR_SYSTEM_URL}</string>
    <string name="cyberark_account_host_url">{YOUR_HOST_URL}</string>
    <string name="cyberark_account_client_id">{YOUR_CLIENT_ID}</string>
    <string name="cyberark_account_app_id">{YOUR_APP_ID}</string>
    <string name="cyberark_account_response_type">code</string>
    <string name="cyberark_account_scope">All</string>
    <string name="cyberark_account_redirect_uri">demo://{YOUR_HOST_NAME}/android/{YOUR_APP_PACKAGE_NAME}/callback</string>
    <string name="cyberark_account_scheme">demo</string>

Step 8: Replace {YOUR_APP_PACKAGE_NAME} with your actual application's package name.


Step 9: Define the Manifest Placeholders for the CyberArk Identity Host and CyberArk Identity Scheme

These manifest placeholders are used internally by the library to register an intent-filter. Go to your app/build.gradle file and add the manifestPlaceholders line as shown below:

android {
    defaultConfig {
        manifestPlaceholders = [cyberarkIdentityHost: "@string/cyberark_account_host_url",
                                cyberarkIdentityScheme: "@string/cyberark_account_scheme"]





Your tenant URL. This is provided when you register your Android app.


The authorization server where your tenant is hosted.


An ID that Identifies your app in CyberArk Identity. This is provided when you register your app as a client.


A unique key is used to build the OAuth2 endpoint URL.


The type of response requested from the authorization server. This must be set to code for authorization code flow.


The specific scopes that are being requested.


The URL that a user is directed to after successful authentication.


The custom scheme implemented for redirection.

Start the authorization flow

First, the authentication client must have a configuration to interact with the CyberArk Identity Server. The Android app redirects the user to CyberArk Identity for authentication. To request authorization, the Android app must redirect the user (browser) to make a secure HTTP call to the authorization endpoint with the following parameters.

Step 1: Create a builder object as shown below:

val cyberArkAccountBuilder = CyberArkAccountBuilder.Builder()

Step 2: Set up a view model and start the authentication code flow

Use the CyberArkAuthProvider class, and the CyberArkAccountBuilder parameter to set up a view model and start the authentication flow. The start authentication code flow pattern is as follows:

val authResponseHandler: LiveData<ResponseHandler<AuthCodeFlowModel>> =

Step 3: Declare the observer instance that will receive the authentication result.

authResponseHandler.observe(this, {
          when (it.status) {
              ResponseStatus.SUCCESS -> {
              ResponseStatus.ERROR -> {
              ResponseStatus.LOADING -> {

Step 4: Launch the authorized URL in a Custom Tab

The Identity Android SDK is enabled with the ability to open the CyberArk Identity sign-in web page to perform the user authentication in a browser window.

  • After authentication, the app redirects the user back to the app to exchange the received authorization code for an access token and/or refresh token.

Step 5: Use device storage for access and refresh tokens

Save the access token and/or refresh token in device storage (SharedPreference) using Keystore encryption.
The Keystore encryption model is as follows:


Step 6: Verify token expiry from the access token

Decode the access token to get the expiry time of the token. The following code sample validates and returns the status of the existing access token.

val status = JWTUtils.isAccessTokenExpired(accessTokenData)

Step 7: Refresh the token

Use the refresh token to obtain a new access token.

val refreshTokenResponseHandler: LiveData<ResponseHandler<RefreshTokenModel>> =
    CyberArkAuthProvider.refreshToken(cyberArkAccountBuilder).start(this, refreshTokenData)

Refer to Refresh Token for details.

Verify your Android device

The CyberArk Identity Android SDK is enabled with an enrollment model that verifies an Android device. The enrollment model allows you to build your Android app with the ability to enroll new devices when a QR code or biometric option is used in the login flow. The enrollment model is as follows:

val authResponseHandler: LiveData<ResponseHandler<EnrollmentModel>> =
      CyberArkAuthProvider.enroll().start(this, accessTokenData)

Scan a QR Code to sign in to CyberArk Identity

The CyberArk Identity Android SDK is enabled with the ability to present highly secure and trusted Multi-factor authentication (MFA) to your Android app. The QR code authentication mechanism allows a call to the authentication (tokens) endpoints by scanning a QR code using your Android device. Use the following procedure to register your new device for MFA.

Step 1: Register your Android app for use with MFA

You can enable your Android app to securely verify user identity by using a mobile device as a second-factor for authentication, an extra security step in the authentication process. After the user signs in, you provide the option to opt-in for a QR code Authenticator before signing in to CyberArk Identity. Refer to the following steps for the authentication flow:

  1. Select QR code Authenticator on the Android device.
  1. Allow the built-in camera app to open.
  2. Open your organization's Sign In page.
  3. Point the camera at the QR Code.
  4. Scan QR code graphic on the Sign In page from your mobile app.
  • This allows SDK functions to call authentication endpoints using the scanned data and the received access token; CyberArk Identity verifies and authenticates the end-user.

Step 2: Implement the QR code Authenticator flow

Use CyberArkQRCodeLoginActivity class to implement the flow. The QR code login model is as follows:

// Start QR Code authenticator Activity
private fun startQRCodeAuthenticator() {
    val intent = Intent(this,
    intent.putExtra("access_token", accessTokenData)
// Callback to handle QR Code Authenticator result
private val startForResult =
    registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        if (result.resultCode == Activity.RESULT_OK) {
            // Use key "QR_CODE_AUTH_RESULT" to receive result data
            val data ="QR_CODE_AUTH_RESULT")
            // Show QR Code Authenticator result using Toast

Use push notifications for authentication

CyberArk Identity MFA delivers push notifications to a user’s pre-registered device using FCM (Firebase Cloud Messaging). Using push notifications, users can immediately allow or deny access to web applications.

Tenant configuration requirements

The following tenant configurations are required to leverage an FCM account:

  • Mobile.Custom.Fcm.Enabled = true
  • Mobile.Custom.Fcm.ApiKey = FCM ServerKey
  • AndroidPushNotificationProvider = Fcm

Step 1: Get FCM token from Firebase (FCMTokenUtil.kt)

    .addOnCompleteListener(OnCompleteListener { task ->
        if (!task.isSuccessful) {
            Log.w(TAG, "Fetching FCM registration token failed", task.exception)
            [email protected]

        // Get new FCM registration token
        val token = task.result
        Log.d(TAG, "Recieved token $token")           

Step 2: Upload FCM token to CyberArk server (FCMService.kt)

val sendFCMTokenModel: SendFCMTokenModel? =
        .start(applicationContext, token, accessTokenData)
                    .start(applicationContext, token, accessTokenData)

Step 3: Configure FCM Service (FCMService.kt)

  1. Parse remote message:
val notificationDataModel: NotificationDataModel =
  1. Verify application state and show notification:
 * if application is in foreground process the notification in activity
if (AppUtils.isAppOnForeground()) {
    Log.i(TAG, "FCMService() App in foreground")
    val intent = Intent(this,
    intent.putExtra(FCMReceiver.NOTIFICATION_DATA, notificationDataModel)
} else {
     * if the application is in the background build and show Notification
    Log.i(TAG, "FCMService() App in background")

Step 4: Build Notifications (FCMManager.kt)

val notificationBuilder = NotificationCompat.Builder(context, channelId)
  1. Perform an Approve action:
val approveIntent = Intent(context,
approveIntent.action = FCMReceiver.ACTION_APPROVE
approveIntent.putExtra(FCMReceiver.NOTIFICATION_DATA, notificationDataModel)
  1. Perform a Deny action:
val denyIntent = Intent(context,
denyIntent.action = FCMReceiver.ACTION_DENY
denyIntent.putExtra(FCMReceiver.NOTIFICATION_DATA, notificationDataModel)
  1. Perform a Body action:
val intent = Intent(context,
intent.putExtra(FCMReceiver.NOTIFICATION_DATA, notificationDataModel)

Step 5: Handle the Push Notification MFA challenge (NotificationActivity.kt)

Submit the OTP code and notification payload to the CyberArk server as shown below.

val submitOTPModel = CyberArkAuthProvider.submitOTP(setupFCMUrl(context))
    .start(context, accessTokenData, otpEnrollModel, notificationPayload)

Use advanced biometric authentication

The CyberArk Identity Android SDK is enabled with the ability to deliver biometric identity services with advanced biometric data processing. The biometric identity service enables your Android app to securely confirm identities using a seamless user sign in flow. Authentication can be enabled during the initial setup with device registration. To register a device:

  • Invoke a strong biometric authentication dialog at app startup.
  • Invoke a strong biometric authentication dialog when the access token expires.

Invoke a Biometric utility instance

In order to register biometric, use the following code sample:

var cyberArkBiometricPromptUtility = CyberArkBiometricManager().getBiometricUtility(biometricCallback)

Show biometric options

The following code sample shows all the strong biometric options available on your device.

cyberArkBiometricPromptUtility.showBioAuthentication(this, null, "Use App Pin", false)

To start the service, register a biometric authentication callback using the CyberArkBiometricCallback interface. The biometric call model is as follows.

private val biometricCallback = object : CyberArkBiometricCallback {
           override fun isAuthenticationSuccess(success: Boolean) {
           override fun passwordAuthenticationSelected() {
           override fun showErrorMessage(message: String) {
           override fun isHardwareSupported(boolean: Boolean) {
           override fun isSdkVersionSupported(boolean: Boolean) {
           override fun isBiometricEnrolled(boolean: Boolean) {
           override fun biometricErrorSecurityUpdateRequired() {

Show available biometric authentication options

The following code snippet demonstrates how to implement biometric authentication for the first time. Use the code below as a reference.

var bioMetric = CyberArkBiometricManager().getBiometricUtility(biometricCallback)
/*Show all the strong biometric authentication options on prompt*/
  bioMetric.showBioAuthentication (this, null, "Use App Pin", false)

Logout client session from the browser

Call the end-session endpoint from the CyberArk Identity to clear the access token from your custom tab browser using the CyberArkAuthProvider class and the CyberArkAccountBuilder parameter. The logout model is as follows:


Remove the access token and the refresh token from device storage (SharedPreference)
using CyberArkPreferenceUtil class.