Posted by on May 20, 2016 in #AndroidDev, #Azure | 6 comments

If you have ever come across Azure Active Directory and integrating it into your own applications and services – you might have used the Active Directory Authentication Library (ADAL). If you haven’t, and you want to get started with this library in the Android ecosystem – this post is for you. Although everything we will create in this blog post can be done without any libraries, it is not encouraged. Using ADAL you will gain an abstraction layer above the complex nature of authentication, so that you can focus on the things you actually want to spend your time on. Throughout this blog post I will be using Android Studio, which is something you can grab for free here: https://developer.android.com/studio/install.html

Learn more about ADAL here: https://azure.microsoft.com/en-us/documentation/articles/active-directory-authentication-libraries/

You will also need to register your application (Native Client Application) in Azure AD to follow along. You can learn more about doing this here:

Create the Project

To get started, let’s create the application project. Launch Android Studio.

  • If you’re in the Welcome Dialog, choose Start a new Android Studio Project. If not, choose File and New Project.
  • Fill out the Application Name, Company Domain and Project Location and click Next.
  • Choose Phone and Tablet and set the Minimum SDK to at least API 14 (IceCreamSandwich). Click Next.
  • As for the first Activity, we will simply pick an Empty Activity. Click Next.
    android1
  • Let the Activity Name and Layout Name stay the same. Click Finish. 

This will create the necessary files and project structure for your new application. Now we are ready to configure the project.

The first thing we need to do is to get ADAL into our project. This can be done in many different ways (cloning the library from GitHub, Maven, Gradle, etc.) and if you already know your way around your tools – get ADAL! If not, no worries, we will go through it using Gradle.

  • In the Project window, find and expand the Gradle Scripts section.
  • Get into the build.gradle module file. Noted by the “(Module: app)” part.
    android2
  • Add the mavenCentral repository from where the library can be downloaded. Put it after the android section and before the dependencies section:
  • Add the ADAL dependency inside the dependencies section:
  • Your build.gradle file should now look something like this:
  • Finally you need to run the Gradle Scripts, you do this by hitting the Sync Now button that shows up in the top right corner.
    android3

This will get ADAL downloaded and added to your project – easy peasy!

Manifest and Code

The final piece of configuration we need to add is in the manifest. We will add the permissions required by ADAL to access the network and the ADAL Activity. This Activity is essentially the view that will allow the user to sign in. Because ADAL takes care of this, we can spend time on building our app, which is great!

  • In the Project window. Find the manifests folder in the app folder. Open the AndroidManifest.xml file.
  • Inside the manifest tag, before the application tag. Add the following two permissions:
  • Inside the application tag, add the ADAL Activity after the activity tag for your MainActivity:
  • Your AndroidManifest.xml file should now look something like this:

Alright, let’s get coding! I will walk you through what to do step by step, and explain the flow when everything has been put together at the end.

  • In the app folder, find the MainActivity class file. It will be located in the java folder, in the folder named after your company domain and application name.
    android4
  • At the top of your class file, we need to import a few things (both ADAL, some Exception objects and Android utilities):
  • Inside the MainActivity class, at the top, add the following constants and variables. Make sure that you have registered your application in Azure AD before doing this. Get the the Client ID, Redirect URI from the Azure AD application and replace the values in the snippet. Learn more about doing this here: http://simonjaeger.com/microsoft-graph-authentication-with-azure-ad/
  • In the onCreate method, add the following snipped below the setContentView method call.
  • Lastly, add the the following onActivityResult method override below the onCreate method.
  • Your MainActivity class file should now look something like this:

So what’s going on here? The onCreate method is called whenever the MainActivity is getting created. So essentially we prompt the user right away for a login by putting our code in here. We have to wrap everything in a try/catch block as the calls may throw a few exceptions that we might need to handle. In the try/catch block we do the following:

  • We create an AuthenticationContext, this is the primitive that represents the authority, which is your Azure AD tenant.
  • We call the acquireToken method. This will start the entire flow by showing the user some UI (as requested by the PromptBehavior.Always parameter). Notice that pass the MainActivity into the constructor of the AuthenticationContext and the acquireToken method – this is because we need to communicate back to the Activity when parts of the flow has completed. That’s why we implemented the onActivityResult method at the bottom. Inside of it, we need to pass the information back to ADAL, so it can continue the authentication flow.
  • In the AuthenticationCallback we implemented the onSuccess method – which simply prints the id token and access token to the Android Monitor.
  • At this point, we are ready to use these tokens for whatever we might need to.

Once you have grasped the concept of ADAL – I would encourage you to implement a better pattern for acquiring the tokens. It’s very straight forward, but it creates a better user experience:

  • Create your AuthenticationContext with an ITokenCacheStore object (e.g. DefaultTokenCacheStore, FileTokenCacheStore, MemoryTokenCacheStore, or your own implementation).
  • Call the acquireTokenSilent method.
  • Validate the response (AuthenticationResult). If it failed, now call the acquireToken method and show UI.
  • Now use the acquired tokens as needed.

This will minimize the need for prompting the user for credentials, by allowing ADAL to cache the data required to grant you tokens silently.

Now run your application by clicking on the Debug button (you can click Run in the menu and click on the Debug ‘app’ button). Your app will start, prompt you to sign in and finally display the tokens in the Android Monitor.

android5

Simple! ADAL is a great way to abstract the complex nature of authentication in your app. It gets you going fast, and it gets you back to building the best app that you can – which is really what we all want! You can find samples, documentation, releases and more for ADAL for Android at this GitHub repository: https://github.com/AzureAD/azure-activedirectory-library-for-android 

-Simon Jaeger