Get Started with Android Authentication Using Kotlin
Tags: kotlin, android, security, mobile
Published: 2022-08-04 12:40:47

### A step-by-step tutorial on using Auth0 and Kotlin to implement basic login/logout in Android apps

### <br>

<img src="https://images.ctfassets.net/23aumh6u8s0i/14fkTCEGztKWNiiCcbygJV/0294154ea2f4095f6af4167f279b0f85/android_icon.png" align="right" width="200" height="200" />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:

![The app’s “Welcome” screen. The “Log In” button is enabled, and the “Log Out” button is disabled.](https://images.ctfassets.net/23aumh6u8s0i/5rQ3FxlB0gfZx19Vcx43dP/8446f93ff34b9969181a2773a0037dc7/welcome_screen.png)

Pressing the _Log In_ button takes the user to the [Auth0 Universal Login screen](https://auth0.com/docs/login/universal-login). It appears in a web browser view embedded in your app. Here’s what it looks like in an emulator...

![The default Auth0 Universal Login web page, as viewed in an emulator, with Auth0 logo and “email address” and “password” fields.](https://images.ctfassets.net/23aumh6u8s0i/6s273BfhhjTQIuE28lBATj/dd80dddaad0a2dd2909c43335924cbeb/universal_login_on_emulator.png)

...and here’s what it looks like on a device:

![The default Auth0 Universal Login web page, as viewed in an emulator, with Auth0 logo and “email address” and “password” fields.](https://images.ctfassets.net/23aumh6u8s0i/5C60xzAH53H4HyxK44nfLu/fb58806460a6217bcc12b33c3ccc7120/universal_login_on_phone.png)

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](https://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.](https://auth0.com/docs/universal-login/new-experience/universal-login-page-templates)

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:

![Universal Login displaying the “wrong email or password” message.](https://images.ctfassets.net/23aumh6u8s0i/4hcbNDhtJUhzankWAqbKGr/7c311ec723d6672d89285a153b4b11fb/universal_login_-_wrong_email_or_password.png)

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 App’s “Welcome” screen, with Snackbar that reads “You need to log in to use the app.”](https://images.ctfassets.net/23aumh6u8s0i/BT6NEQW0o2kwM2w8lSlQP/bdfe6d004802142d68bc8f588baf50e0/authentication_canceled.png)

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:

![The app in its “logged in” state. The “Log In” button is disabled, the “Log Out” button is enabled, and the app’s other controls are visible.](https://images.ctfassets.net/23aumh6u8s0i/3ZSDcJTymsLEzcUGaufsi/76d9c143ec91c3aae8b3746671f7bbc3/logged_in_screen.png)

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:

![The app is in its “logged out” state. The “Log In” button is enabled, the “Log Out” button is disabled, and the app’s other controls are hidden.](https://images.ctfassets.net/23aumh6u8s0i/5YISprqJjBLtGRrIJGAO4h/2b59056f34a7cab636f42663547fe8d2/logged_out_screen.png)

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 <a href="https://auth0.com/signup" data-amp-replace="CLIENT_ID" data-amp-addparams="anonId=CLIENT_ID(cid-scope-cookie-fallback-name)">sign up for a free account</a>, 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.**](https://www.oracle.com/java/technologies/javase-jdk16-downloads.html) You can find out which version is on your computer by opening a command-line interface and entering `java --version`.
* [**Android Studio,**](https://developer.android.com/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:
    1. Open _Tools_ → _AVD Manager_ (AVD is short for “Android Virtual Device”). The _Your Virtual Devices_ window will appear. Click the _Create Virtual Device..._ button.
    2. The _Select Hardware_ window will appear. In the _Phone_ category, select _Pixel 3a_ and click the _Next_ button.
    3. 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.
    4. 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.
    5. 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*](https://developer.android.com/courses/android-basics-kotlin/course) 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](https://github.com/auth0-blog/get-started-android-authentication-kotlin/archive/refs/heads/main.zip) (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:

![The starter app’s initial screen.](https://images.ctfassets.net/23aumh6u8s0i/5rQ3FxlB0gfZx19Vcx43dP/8446f93ff34b9969181a2773a0037dc7/welcome_screen.png)

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:

1. Add the app to your Auth0 dashboard’s list of registered applications.
2. 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.
3. 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._**](#add-the-app-to-the-applications-list)


### If you don’t have an Auth0 account yet...

🛠 <a href="https://auth0.com/signup" data-amp-replace="CLIENT_ID" data-amp-addparams="anonId=CLIENT_ID(cid-scope-cookie-fallback-name)">**...go ahead and sign up for one!**</a> It’s free, and we’ve taken great care to make the process as painless as possible.


### <a id="add-the-app-to-the-applications-list"></a>Add the app to the Applications list

🛠 In the left side menu of the [Auth0 dashboard](https://manage.auth0.com/), click on _Applications_:

![The main page of the Auth0 dashboard. The reader is directed to expand the “Applications” menu.](https://images.ctfassets.net/23aumh6u8s0i/2PsBUajhnnXWJR7QS8PUfg/e9c6bd92175335286aa03224e1646e91/expand_applications_menu.png)

🛠 This will expand the _Applications_ menu. Select the first item in that menu, which also has the name _Applications_:

![The main page of the Auth0 dashboard, with the “Applications” menu expanded. The reader is directed to select the “Applications” menu item.](https://images.ctfassets.net/23aumh6u8s0i/2UNcUhGNq16RFBJkokz7KS/854f3e92fbe58943bf05f0f4a761d177/select_applications_menu_item.png)

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:

![The “Applications” page. The reader is directed to click the “Create Application” button.](https://images.ctfassets.net/23aumh6u8s0i/4aOFH6mt7xs9CspYNkuU7Q/1cff580b803c09236ad959b18614119a/create_application.png)

You’ll see this dialog appear:

![The “Create application” dialog. The application’s name is set to “Android Login” and the selected application type is “Native.”](https://images.ctfassets.net/23aumh6u8s0i/3qROPPPGeZtrzmBzZO6WCE/e21feef8afbfd11519eda926364a8861/create_application.png)

🛠 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:

![The “Quick Start” page. It contains several icons representing an operating system or platform.](https://images.ctfassets.net/23aumh6u8s0i/5WJxrAnoNxMIg2JDy9PrPK/4ac903e67ebdb15a2a806f87caf50b31/android_login_-_quickstart.png)

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:

![The “Application” page’s “Settings” tab. The reader is directed to copy the values of the “Domain” and “Client ID” text fields](https://images.ctfassets.net/23aumh6u8s0i/7AJDgycObPWPe1i7krH2K0/a2de61d00f9c3b8e5365fda5233efd98/android_login_-_settings.png)

You’re going to do two critical things on this page:

1. Get information that the app needs to know about Auth0, and
2. 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:

![The “Application URIs” section of the page. The reader is told that they’ll need to fill out the “Allowed Callback URLs” and “Allowed Logout URLs” fields.](https://images.ctfassets.net/23aumh6u8s0i/1sCD6Kqve9WpbMBO4jh9PA/78710d64772f84bbcf9ad61c5903adce/callback_and_logout_url_fields.png)

This is where you provide two pieces of information that Auth0 needs to know about the app, which are:

1. A **callback URL:** the URL that Auth0 will redirect to after the user successfully logs in. There can be more than one of these.
2. 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?_](https://auth0.com/blog/url-uri-urn-differences/)

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}` with `app`. `{SCHEME}` is the URL’s protocol, and if you were writing a web app, this value would be `http`, or better, `https`. Since this is an Android-native app, you can pick any string for this value. I like to use `app`.
* 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 is `com.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:

![The bottom of the page features the “Save Changes” button. An arrow directs the reader to click the button.](https://images.ctfassets.net/23aumh6u8s0i/3w6HT6fNOjiJPOjA5uduzt/bb290473a3ae601b70d7ce6456ac7fc4/settings_-_save_changes.png)


### 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_:

![The bottom of the page. An arrow directs the reader to expand the “User Management” menu.](https://images.ctfassets.net/23aumh6u8s0i/13qs824Uauwv78ewd682EO/6898da1b68642b10cb9c31413f358a95/user_management_menu.png)

🛠 This will expand the _User Management_ menu. Select the Users item in that menu:

![The bottom of the page now features an expanded “User Management” menu. An arrow directs the reader to expand the “Users” menu item.](https://images.ctfassets.net/23aumh6u8s0i/1tivj870qehY6oIaeDolj1/31b0544fab715b7fbded29fb63802a45/select_users_menu_item.png)

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.

![The “Users” page. The page says, “You don’t have any users yet.” An arrow directs the reader to click the “Create User” button.](https://images.ctfassets.net/23aumh6u8s0i/1wCORw3pqSOLt65n48Qr56/7421164d02cfb112350882a4cccb4cca/click_create_user.png)

🛠 Click the _Create User_ button to create a new user, which will make this dialog box appear:

![The “Create User” dialog. It has fields for email and password, as well as a drop-down menu displaying “Username-Password-Authentication.”](https://images.ctfassets.net/23aumh6u8s0i/2s3GfTHNKRgts8lcXQJ0SH/6d6d0ca397684be75030d40bb6b94fb5/create_user_dialog.png)

🛠 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:

![The user’s “Details” page.](https://images.ctfassets.net/23aumh6u8s0i/3TbGcAFo4e4N1coNCtHYdV/fa830264079fc661cbc683590729e4b1/user_details_page.png)

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.


[Read more...](https://auth0.com/blog/get-started-android-authentication-kotlin/?utm_source=content_synd&utm_medium=sc&utm_campaign=global_dist)