Using OIDC for Easy Android Login

In modern mobile apps, a dedicated auth page is a must. Users want the apps they love to be personalized and expect to be able to use services on different devices and platforms without a hassle. More important than this, they want to know that their data is secure.

When working on Android, the implementation process for secure login can be complex, as many different parts need to align correctly for it to work. On the Android side, you need to create an easy and engaging login UI, communicate with a back-end service, securely persist the user data, and maintain that data, as the user expects a single sign-on experience. In addition to that, you will need to have a back-end app for supporting the login feature in a secure and efficient way. 

Here is where the Okta OIDC SDK comes in! As a mobile SDK developed by industry-leading security experts, the Okta OIDC SDK is designed to provide a simple alternative for your users to log into your app. By using OAuth 2.0 and OpenID Connect (OIDC), this is made easy, as these are the security industry’s standards for authorization and authentication. To learn more, consider reading An Illustrated Guide to OAuth and OpenID Connect.

This tutorial will walk you through the simple steps to set up the Okta OIDC SDK on Android, leaving you with a working app that allows for secure login.

Create an Android Login Application

To begin, create a new Android app. It will consist of three screens:

  • Splash screen where you figure out if the user is already logged in or not.
  • Login screen.
  • Home screen, which is only accessible to the logged-in users.

First, you’ll need to download and install the latest version of Android Studio (v4.1.1 at the time of this writing).

Next, launch the app and navigate to FileNew…New Project…. Then, create an “Empty Activity” for “Phone and Tablet.” You should now see a screen similar to this:

Change your application name and add the right package name, set the minimum SDK to API 23, and click Finish to create the project.

Add the Okta Android OIDC SDK

Android apps use Gradle as their build tool. To add the Okta OIDC SDK as a dependency to your project, you will need to modify the app module’s build.gradle file:

You need to add the right auth redirect scheme for your Okta app and add the Okta library as a dependency. Make sure the applicationId matches what you used when creating your app.

  1. The redirect URI for the application you created in your Okta Developer Console.
  2. We are using a view binding feature to interact with our views. More information can be found here.
  3. Okta OIDC libraries require Java 1.8 compatibility.
  4. Add the dependency required for the Okta OIDC library.

Sync the project with Gradle files by clicking the FileSync Project with Gradle Files, so the Okta dependency gets downloaded.

Install the Okta CLI

Getting started with Okta is made quite straightforward with the help of the Okta CLI. It’s a tool that makes creating an Okta account and an Okta application a breeze!

The Okta CLI is available for macOS, Linux, and Windows.

MacOS (via Homebrew)

Linux (via Flatpak)

Windows (via Chocolatey)

If you don’t want to use a package manager, you can install the Okta CLI with curl and bash.

Register Your Android Application

To create an Okta developer account, simply run the following command:

You will be prompted with a few questions:

(1) This is your Okta domain; you will need it later

(2) Enter the code you receive in your email.

(3) Click on this link to change your password. You will need these credentials for this example

Create an Okta OIDC App

To create a new Okta OIDC app, run the following command:

You will be prompted with a few questions:

(1) Name your Okta app

(2) Native app (mobile) is the option to select for Android applications.

(3) Press enter for the default value. You will need this value for the Okta library setup.

(4) Press enter for the default value. You will need this value for the Okta library setup.

(5) You will need this ID for the initialization of the Okta library in your application

Create an Android Application Class

In the root folder of your app’s package (in the provided example, that’s the folder app/src/main/java/dev/dbikic/oktaloginexample) create a Kotlin application class named`OktaLoginApplication`.

For now, just create the class and make it extend the Application class from the Android framework.

(1) Update the package to match the one you set when creating the project.

After creating the application class, you need to reference it in your app/src/main/AndroidManifest.xml file:

(1) Okta OIDC SDK needs internet permission to communicate with the back-end

(2) Reference the application class you created in the previous step.

Manage Authentication With a Manager Class

When adding third-party libraries to your codebase, it’s usually a good idea to create a wrapper class that will hide the actual usage. Reasons for this include:

  • Reusing of the common interaction with the libraries.

  • You can define all the library interactions in an interface and provide the actual implementation with dependency injection throughout your app.

  • Everything related to that library is in one place. Replacing the library with a different one is easy as you only need to change the wrapper class.

Because the above, create a class called OktaManager in the root package. This class will be used in all the screens you create:

(1) private lateinit var webAuth: WebAuthClient is a reference to the web client you will invoke to log in.

(2) private lateinit var sessionClient: SessionClient refers to the session you can use to conduct multiple operations after logging in, such as getting the user’s profile, revoking the authentication token, refreshing the authentication token, etc.

(3) Replace with your client ID.

(4) Replace with your discovery URL.

(5) Replace with your redirect URL.

(6) Replace with your end session redirect URL.

(7) setRequireHardwareBackedKeyStore(true) forces the app to require a device with encryption capabilities. This is the default configuration for Okta OIDC, and it’s considered the best practice. If you want to run this code in an emulator, though, you can temporarily set it to false.

The last step of the setup stage will be to initialize the OktaManager. Remember the empty OktaLoginApplication class? Now you need to modify it to initialize the manager when the app is created.

That’s it! Now, let’s create the screens.

Add an Android Splash Screen

The purpose of a splash screen is to initialize all the applications’ dependencies and prepare the app for usage. You’ll use it to figure out if the user is authenticated and decide which screen to show next: the login screen or the home screen.

Create a SplashActivity class in the root package.

(1) For simplicity, the instance of the OktaManager class is in the application class so that it can be easily accessed from all the activities. The real-world solution here would be to use dependency injection and inject the instance class

(2) Ignore the unresolved reference error for now because we will add the missing class in the next step.

Register the activity in the AndroidManifest.xml file:

(1) This intent filter specifies that the SplashActivity is the first activity that will be shown when the app is launched.

This class won’t compile just yet. You’ll need to create HomeActivity and LoginActivity classes before it does.

Build an Android Login Screen

Now, let’s do the LoginActivity! First, create a simple layout with a button in app/src/main/res/layout/activity_login.xml:

Then, create the LoginActivity class in a new ui package:

(1) Register the auth callback with the OktaManager.

(2) Call the sign-in method when the button is clicked.

(3) The result is an AuthorizationStatus object. With a simple when expression we can quickly figure out the status type and access its members if needed.

And register it in the AndroidManifest.xml:

The purpose of the LoginActivity is to try to authenticate the user with Okta when the login button is pressed. To achieve that, you need to register the web auth callback with the Okta OIDC SDK, and call the signIn() method.

This is enough for the SDK to open a custom Chrome tab with the login screen of the Okta application. Users input their credentials into the form, and when the process is finished, the appropriate method of your auth callback will be called. This allows you to gracefully handle the possible errors or handle the login success, which is, in this case, navigating to the HomeActivity.

Create an Android Home Screen

HomeActivity is the part of your app which can be accessed only by authorized users. In this example, you can fetch the user details, display the user name on the UI, and sign the user out of the app. First, create the layout file in res/layout/activity_home.xml:

Then, create the HomeActivity:

(1) Register the user profile callback with the OktaManager.

(2) Sign out from the app on the sign out button.

(3) After the user is successfully logged out from Okta, clear the user’s data.

(4) Navigate the user back to the LoginActivity after they sign out.

(5) This flag makes sure that all the back stack activities are cleared and that the LoginActivity will be the only activity in the memory.

(6) You have fetched the user info successfully! You can check which fields you received here.

And register it in the AndroidManifest.xml:

You can now implement the empty method navigateToHome() in both SplashActivity and LoginActivity.

Run Your Android Application

Now it’s time to run the application on an emulator or on a physical device, by pressing the play icon in the top right part of Android Studio. Your app and its login process should look similar to the video below:

What’s cool about the Okta OIDC SDK is that it also securely stores the user session to the app’s local storage and maintains its state for you. Instead of creating a custom user management system and handling multiple edge-cases that can happen in the real world, you can concentrate on spending your time building app features for your users.

You also implemented the logout flow, which is triggered by the user clicking the Log Out button:

Learn More About Android and OIDC

This post showcased how easy it is to set up and use the Okta OIDC SDK for an Android app. The functionalities which the SDK brings to your app, like the OAuth 2.0 authorization and OpenID Connect authentication, are essential for a modern-day app with challenges like security and data privacy.

Creating a custom solution for security and privacy is challenging and time-consuming since the code on the mobile part is not enough, and you also need to have a back-end app that supports those features. Maintaining two applications can cause a lot of long-term work.

You can find the source code for this example on GitHub, in the oktadeveloper/okta-android-login-example repository.

This UrIoTNews article is syndicated fromDzone