Quickstart: Sign in users and call the Microsoft Graph API from an Android app

Applies to:
  • Microsoft identity platform endpoint
  • Microsoft Authentication Library (MSAL)

For a general availability (GA) library, use the Azure Active Directory (Azure AD) v1.0 endpoint and Azure AD Authentication Library (ADAL). For more info, see About v1.0.

This quickstart contains a code sample that demonstrates how an Android application can sign in personal or work and school accounts, get an access token, and call the Microsoft Graph API.

Shows how the sample app generated by this quickstart works

Note

Prerequisites

  • Android Studio
  • Android 16+ is required

Register and download your quickstart app

You have two options to start your quickstart application:

Option 1: Register and auto configure your app and then download your code sample

Step 1: Register your application

To register your app,

  1. Go to the new Azure portal - App registrations pane.
  2. Enter a name for your application and select Register.
  3. Follow the instructions to download and automatically configure your new application with just one click.

Option 2: Register and manually configure your application and code sample

Step 1: Register your application

To register your application and add the app's registration information to your solution manually, follow these steps:

  1. Navigate to the Microsoft identity platform for developers App registrations page.
  2. Select New registration.
  3. When the Register an application page appears, enter your application's registration information:
    • In the Name section, enter a meaningful application name that will be displayed to users of the app, for example AndroidQuickstart.
    • You can skip other configurations on this page.
    • Hit the Register button.
  4. Click on the new app > go to Authentication > Add Platform > Android.
    • Enter the Package Name from your Android studio project.
    • Generate a Signature Hash. Refer to the portal for instructions.
  5. Select Configure and save the MSAL Configuration JSON for later.

Step 1: Configure your application

For the code sample for this quickstart to work, you need to add a redirect URI compatible with the Auth broker.

Already configured Your application is configured with these attributes

Step 2: Download the project

Step 3: Configure your project

If you selected Option 1 above, you can skip these steps.

  1. Extract and open the Project in Android Studio.

  2. Inside app > src > main > res > raw, open auth_config.json.

  3. Edit auth_config.json and replace it with the JSON from the Azure portal. If instead you want to manually make the changes:

    {
       "client_id" : "Enter_the_Application_Id_Here",
       "authorization_user_agent" : "DEFAULT",
       "redirect_uri" : "Enter_the_Redirect_Uri_Here",
       "authorities" : [
          {
             "type": "AAD",
             "audience": {
                "type": "Enter_the_Audience_Info_Here",
                "tenant_id": "Enter_the_Tenant_Info_Here"
             }
          }
       ]
    }
    
  4. Inside app > manifests, open AndroidManifest.xml.

  5. Paste the following activity to the manifest\application node:

    <!--Intent filter to catch Microsoft's callback after Sign In-->
    <activity
        android:name="com.microsoft.identity.client.BrowserTabActivity">
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="msauth"
                android:host="Enter_the_Package_Name"
                android:path="/Enter_the_Signature_Hash" />
        </intent-filter>
    </activity>
    
  6. Run the app!

Note

This quickstart supports Enter_the_Supported_Account_Info_Here.

  1. Extract and open the Project in Android Studio.
  2. Inside app > res > raw, open auth_config.json.
  3. Edit auth_config.json and replace it with the JSON from the Azure portal. If instead you want to manually make these changes:
    "client_id" : "ENTER_YOUR_APPLICATION_ID",
    "redirect_uri": "ENTER_YOUR_REDIRECT_URI", 
    
  4. Inside app > manifests, open AndroidManifest.xml.
  5. Add the following activity to the manifest\application node. This code snippet registers a BrowserTabActivity to allow the OS to resume your application after completing the authentication:
    <!--Intent filter to catch Microsoft's callback after Sign In-->
    <activity
        android:name="com.microsoft.identity.client.BrowserTabActivity">
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="msauth"
                android:host="Enter_the_Package_Name"
                android:path="/Enter_the_Decoded_Signature_Hash" />
        </intent-filter>
    </activity>
    
  6. Replace Enter_the_Package_Name and Enter_the_Signature_Hash with the values you registered in the Azure portal.
  7. Run the app!

More Information

Read the following sections for more info about this quickstart.

Getting MSAL

MSAL (com.microsoft.identity.client) is the library used to sign in users and request tokens used to access an API protected by Microsoft identity platform. You can use Gradle 3.0+ to install it by adding the following in Gradle Scripts > build.gradle (Module: app) under Dependencies:

implementation 'com.android.volley:volley:1.1.1'
implementation 'com.microsoft.identity.client:msal:0.3.+'

MSAL initialization

You can add the reference for MSAL by adding the following code:

import com.microsoft.identity.client.*;

Then, initialize MSAL using the following code:

    sampleApp = new PublicClientApplication(
        this.getApplicationContext(),
        R.raw.auth_config);
Where:
R.raw.auth_config This file contains the configurations for your application including your App/Client ID, Sign-in audience, Redirect URI, and several other customization options.

Requesting tokens

MSAL has two methods used acquire tokens: acquireToken and acquireTokenSilentAsync

acquireToken: Getting a token interactively

Some situations require users to interact with Microsoft identity platform. In these cases, the end user may be required to select their account, enter their credentials, or consent to the permissions your app has requested. For example,

  • The first time users sign in to the application
  • If a user resets their password, they will need to enter their credentials
  • If consent is revoked
  • If your app explicitly requires consent.
  • When your application is requesting access to a resource for the first time
  • When MFA or other Conditional Access policies are required
sampleApp.acquireToken(this, SCOPES, getAuthInteractiveCallback());
Where:
SCOPES Contains the scopes being requested (that is, { "user.read" } for Microsoft Graph or { "<Application ID URL>/scope" } for custom Web APIs (i.e. api://<Application ID>/access_as_user)
getAuthInteractiveCallback Callback executed when control is given back to the application after authentication

acquireTokenSilent: Getting a user token silently

Apps shouldn't require their users to sign in every time they request a token. If the user has already signed in, this method allows apps to request tokens silently.

    sampleApp.getAccounts(new PublicClientApplication.AccountsLoadedCallback() {
        @Override
        public void onAccountsLoaded(final List<IAccount> accounts) {

            if (!accounts.isEmpty()) {
                sampleApp.acquireTokenSilentAsync(SCOPES, accounts.get(0), getAuthSilentCallback());
            } else {
                /* No accounts */
            }
        }
    });
Where:
SCOPES Contains the scopes being requested (that is, { "user.read" } for Microsoft Graph or { "<Application ID URL>/scope" } for custom Web APIs (i.e. api://<Application ID>/access_as_user)
getAccounts(...) Contains the Account you're trying to get tokens for silently
getAuthSilentCallback() Callback executed when control is given back to the application after authentication

Next steps

Learn the steps to create the application used in this quickstart

Try out the Android tutorial for a complete step-by-step guide on building applications and new features, including a full explanation of this quickstart.

MSAL for Android library wiki

Read more information about MSAL library for Android:

Help and support

If you need help, want to report an issue, or want to learn more about your support options, see the following article: