A step-by-step tutorial on using Auth0 and Kotlin to implement basic login/logout in Android apps
If you make apps for Android, you’ll eventually have to build one that requires users to log in. This article will show you how to use Auth0 to add fully-featured login and logout to an Android app so that you can focus your time and effort on its actual functionality.
Adding authentication — the more formal term for “login/logout” — only looks simple. It often turns into its own project. Just handling the many ways users want to log in can quickly become an all-consuming task. You’d also have to deal with user management, scaling, and security issues, each having dozens of considerations, risks, issues, and edge cases.
Auth0 solves this problem. With Auth0 and a few lines of code, your app can have a full-featured system that supports logging in with a username/password combination and single sign-on. You’ll also be able to add features such as social accounts, multi-factor authentication, passwordless login, biometrics, and more. You won’t have to update it yourself or handle “behind the scenes” issues, either! Instead, you can concentrate your efforts on what your app does.
Look for the 🛠 emoji if you’d like to skim through the content while focusing on the build and execution steps.
What You’ll Build
You’ll use Auth0 to build a single-screen Android app that allows users to log in and out. I’ve purposely kept it as simple as possible to keep the focus on authentication.
While logged in, the user will be able to see the following information from their user profile:
- Full name
- Email address
- Picture
When you launch the completed app, you’ll see a greeting, a Log In button, and a disabled Log Out button:
Pressing the Log In button takes the user to the Auth0 Universal Login screen. It appears in a web browser view embedded in your app. Here’s what it looks like in an emulator...
...and here’s what it looks like on a device:
When you use Auth0 to add login/logout capability to your apps, you delegate authentication to an Auth0-hosted login page. You've probably seen this in Google web applications such as Gmail and YouTube. These services redirect you to log in using accounts.google.com. After logging in, Google returns you to the web application as a logged-in user.
If you’re worried that using Auth0’s Universal Login means that your app’s login screen will be stuck with the default Auth0 “look and feel,” I have good news for you: you can customize it to match your app or organization’s brand identity.
The Universal Login page saves you from having to code an authentication system. It gives your applications a self-contained login box with several features to provide a great user experience.
If the user enters an invalid email address/password combination, it displays an error message and gives them another chance to log in:
There are two ways to exit the Universal Login screen. There’s the “unhappy path,” where the user presses the Cancel button at the upper left corner of the screen, which dismisses the Universal Login screen and returns them to the opening screen. When the app detects that the user has canceled login, it displays a Snackbar that informs the user that they need to log in to use the app:
The “happy path” out of the Universal Login appears when the user enters a valid email address/password combination. When this happens, Auth0 authenticates the user, the embedded web view and Universal Login will disappear, and control will return to the app, which will now look like this:
Here’s what changed after the user logged in:
- The title text at the top of the screen now says, “You’re logged in.”
- The Log In button is disabled, and the Log Out button is enabled.
- The name, email address, and photo associated with the user’s account appear onscreen.
- A Snackbar displays “Success:” and the user’s name.
As you might expect, the user logs out by pressing the Log Out button, which takes them to this screen:
Note that:
- The text at the top of the screen says, “You’re logged out.”
- The Log In button is enabled, and the Log Out button is disabled.
- The other controls that were visible when logged in are no longer visible.
What You’ll Need
You’ll need the following to build the app:
1. An Auth0 account
The app uses Auth0 to authenticate users, meaning you need an Auth0 account. You can sign up for a free account, which lets you add login/logout to 10 applications, with support for 7,000 users and unlimited logins — plenty for your prototyping, development, and testing needs.
2. An Android development setup
To develop applications for Android, make sure you have the following, in the order given below:
- Any computer running Linux, macOS, or Windows from 2013 or later with at least 8 GB RAM. When it comes to RAM, more is generally better.
-
Java SE Developer Kit (JDK), version 11 or later. You can find out which version is on your computer by opening a command-line interface and entering
java --version
. - Android Studio, version 3.6 (February 2020) or later. I used the current stable version of Android Studio when writing this article: version 2021.2.1, also known as “Chipmunk.”
- At least one Android SDK (Software Development Kit) platform. You can confirm that you have one (and install one if you don’t) in Android Studio. Open Tools → SDK Manager. You’ll see a list of Android SDK platforms. Select the current SDK (Android 11.0 (R) at the time of writing), click the Apply button, and click the OK button in the confirmation dialog that appears. Wait for the SDK platform to install and click the Finish button when installation is complete.
-
An Android device, real or virtual:
- Using a real device: Connect the device to your computer with a USB cable. Make sure that your device has Developer Options and USB debugging enabled.
- Using a virtual device: Using Android Studio, you can build a virtual device (emulator) that runs on your computer. Here’s my recipe for a virtual device that simulates a current-model inexpensive Android phone:
- Open Tools → AVD Manager (AVD is short for “Android Virtual Device”). The Your Virtual Devices window will appear. Click the Create Virtual Device... button.
- The Select Hardware window will appear. In the Phone category, select Pixel 3a and click the Next button.
- The System Image window will appear, and you’ll see a list of Android versions. Select R (API 30, also known as Android 11.0). If you see a Download link beside R, click it, wait for the OS to download, then click the Finish button. Then click the Next button.
- The Android Virtual Device (AVD) window will appear. The AVD Name field should contain Pixel 3a API 30; the two rows below it should have the titles Pixel 3a (a reasonable “representative” phone, released three years ago at the time of writing) and R, and in the Startup orientation section, Portrait should be selected. Click the Finish button.
- You will be back at the Your Virtual Devices window. The list will now contain Pixel 3a API 30, and that device will be available to you when you run the app.
3. A little familiarity with Android development.
If you’re new to Android development or the Kotlin programming language, you might find Android Basics in Kotlin to be a good introduction.
First Steps
Download and run the starter project
To keep this tutorial focused on implementing Auth0 authentication in an Android app, I created a starter project that you can download. It contains an activity with controls already laid out and includes all the necessary files. By starting with this project, you’ll be able to focus on adding login and logout to an app without distractions such as building a user interface.
🛠 Download the .zip file containing the starter and completed projects for the app (257 KB) and uncompress it. This will create a get-started-android-authentication-kotlin-main
folder on your local drive.
🛠 Start Android Studio and open the starter project. Do this by selecting File → Open, navigating to the Android Login (starter)
folder, and clicking the Open button.
The project should take a few seconds to load into Android Studio.
🛠 Confirm that the starter project works. Select a simulator or device from the device menu and run the app. It should look like this:
Right now, the app simply displays the “Welcome” screen. You can press the buttons, but they won’t do anything yet.
Get the App’s Package Name
There’s one more task to perform before we set things up on the Auth0 side: you need to get the app’s package name, the string that uniquely identifies an Android app. For the starter project, the package name is com.auth0.androidlogin
.
If you need to add authentication to an existing Android project, you can use the app’s package name in its project manifest file, which contains information for the build tools and Android operating system.
The manifest file, AndroidManifest.xml
, is an XML file. You can find the app’s package name in that file’s manifest
tag, in its package
attribute. In the example below, the package name is com.example.packagename
:
<!-- Example AndroidManifest.xml file -->
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.packagename">
<!-- The rest of the file goes here... -->
Remember the package name — you’ll use it in the next step! Once again, the app package name in the starter project is com.auth0.androidlogin
.
Register the App in the Auth0 Dashboard
The next step is to register the app in your Auth0 dashboard. In this process, you will:
- Add the app to your Auth0 dashboard’s list of registered applications.
- Gather two pieces of information the app will need to delegate login/logout to Auth0: your tenant’s domain and the client ID that Auth0 will assign to the app.
- Provide Auth0 with the necessary callback URLs to contact the app: one to call at the end of the login process and the other to call at the end of the logout process.
🚨 To perform this step, you’ll need an Auth0 account. 🚨
🛠 If you already have an Auth0 account, log in, skip the next section, and proceed to the part titled Add the app to the Applications list.
If you don’t have an Auth0 account yet...
🛠 ...go ahead and sign up for one! It’s free, and we’ve taken great care to make the process as painless as possible.
Add the app to the Applications list
🛠 In the left side menu of the Auth0 dashboard, click on Applications:
🛠 This will expand the Applications menu. Select the first item in that menu, which also has the name Applications:
You will now be on the Applications page. It lists all the applications that you have registered to use Auth0 for authentication and authorization.
🛠 Let’s register the app. Do this by clicking the Create application button near the top right of the page:
You’ll see this dialog appear:
🛠 You’ll need to provide two pieces of information to continue:
- Enter a name for the app in the name field. It might be simplest to use the same name as your Android Studio project (if you’ve been following my example, use the name
Android Login
). - Specify the application type, which in this case is Native.
Click Create. The Quick Start page for the app will appear:
This page provides ready-made projects for several different platforms you can use as the basis for an application that delegates login/logout to Auth0. You won’t use any of them in this exercise; instead, you’ll use a couple of Auth0 libraries and write the code yourself. It’s more educational — and more importantly, fun — that way.
🛠 Click the Settings tab, which will take you to this page:
You’re going to do two critical things on this page:
- Get information that the app needs to know about Auth0, and
- Provide information that Auth0 needs to know about the app.
Let’s take care of the first one, i.e., getting the information that the app needs, namely:
- The domain. You need it to build the URL the app will use to contact Auth0. It uniquely identifies your Auth0 tenant, a collection of applications, users, and other information you have registered with your Auth0 account.
- The client ID, the identifier that Auth0 assigned to the app. It’s how Auth0 knows which app it’s working with.
🛠 Get this information by copying the contents of the Domain and Client ID fields for later reference. You’ll enter them into your Android Studio project soon.
🛠 Scroll down the page to the Application URIs section:
This is where you provide two pieces of information that Auth0 needs to know about the app, which are:
- A callback URL: the URL that Auth0 will redirect to after the user successfully logs in. There can be more than one of these.
- A logout URL: the URL that Auth0 will redirect to after the user logs out. There can be more than one of these.
In case you were wondering what the difference between a URI and a URL is, we have answers for you in this article: URL, URI, URN: What's the Difference?
You’re probably thinking: “Wait a minute — I’m writing an Android app. It doesn’t have web pages that you navigate to using URLs, but Views with underlying code in Controllers!”
You’re absolutely right. In the case of native applications, the callback and logout URLs are identical strings, and Auth0 sends that string to the app to inform it that a user has logged in or logged out.
The string that native Android apps use for both the callback URL and the logout URL follows this format:
{SCHEME}://{YOUR_DOMAIN}/android/{YOUR_APP_PACKAGE_NAME}/callback
🛠 To construct the string, do the following:
- Replace
{SCHEME}
withapp
.{SCHEME}
is the URL’s protocol, and if you were writing a web app, this value would behttp
, or better,https
. Since this is an Android-native app, you can pick any string for this value. I like to useapp
. - Replace
{YOUR_DOMAIN}
with the value from the Domain field you saw earlier on this page. - Replace
{YOUR_APP_PACKAGE_NAME}
with the app’s bundle identifier. If you didn’t change the package name in the starter project, this value iscom.auth0.Android-Login
.
🛠 Enter the URL you just constructed into both the Allowed Callback URLs and Allowed Login URLs fields. Remember, the same URL goes into both fields.
🛠 You’ve done everything you need to do on this page. Scroll down to the bottom of the page and click the Save Changes button:
Create a user if your tenant doesn’t have any
If you just created an Auth0 account, your tenant is brand new. It won’t have any user accounts, so there won’t be any way to log in to the app. If this is the case, follow these steps to create a user.
🛠 In the menu on the left side of the Auth0 dashboard, click on User Management:
🛠 This will expand the User Management menu. Select the Users item in that menu:
The Users page will appear. It lists all the users registered to your tenant. You’ll see the “You don’t have any users yet” message if there are no users.
🛠 Click the Create User button to create a new user, which will make this dialog box appear:
🛠 Enter an email address and password for the user. The only option for the Connection will be Username-Password-Authentication, so leave it as it is. Make a note of that email address and password — you’ll be using them to log in to the app.
🛠 Click the Create button to create the user. The user’s Details page will appear:
That takes care of all the setting up you need to do within the Auth0 dashboard. It’s time to go back to Android Studio and the app.
Top comments (0)