Use Microsoft Graph in an Android app

Parker Schroeder

Kristen Halper

Hello Android developers,

This week, we’ll be continuing our blog series on using the Microsoft Authentication Library (MSAL) and the Microsoft Graph to connect to M365 services in your own Android apps.

Previously, we covered the basics of MSAL and an introduction to MS Graph for Android, so be sure to check out those posts first!

In this post, we’ll connect all these ideas together by showing you how to call the MS Graph API in Android apps. More specifically, we’ll cover:

  • Review of MSAL authentication
  • Calling the MS Graph API

    • With HTTP libraries
    • With MS Graph SDKs

Review of acquiring tokens with MSAL

Before we jump into code snippets for calling the MS Graph API, let’s review how to acquire a valid access token from MSAL.

As a reminder, after following along with previous blog posts, you should have already:

  • Registered your app in Azure Portal with permissions for MSAL and MS Graph
  • Configured your Android project to use MSAL

Once these prerequisites have been satisfied, you can use MSAL to sign in users and acquire access tokens. If you recall, we finished off the MSAL authentication blog post by creating a PublicClientApplication instance and using it to prompt users for their credentials. Once they were authenticated successfully, we then gained access to an IAuthenticationResult object, which contains the accessToken field that we need today!

For each MS Graph API request, you will have to pass in this accessToken value. You can either store this value after a successful user sign in, or call acquireTokenSilent to make sure the token hasn’t expired.

For readability, our examples in this post will follow the latter approach, but we’d like to note that it’s not required to re-request a token every time you access the API.

So, assuming a user has already been authenticated, our request flow will be:

  • Request token silently
  • On success

    • Get access token from authentication result
    • Perform request

To request a token, you will first need to know the scopes and authority for the token. The scopes are the same as the MS Graph permissions you previously added in Graph Explorer or in your app registration, while the authority is the value you entered in your auth_config_x_account.json files during MSAL config. You’ll also need a reference to the PublicClientApplication object you created when setting up MSAL.

Putting all these pieces together, you get the following code snippet:

  // Set up scopes and authority
  val scopes = arrayOf("user.read")
  val authority = "https://login.microsoftonline.com/common"

  // Create callback to run after token is requested
  val authCallback = object : AuthenticationCallback {
      override fun onSuccess(authenticationResult: IAuthenticationResult) {
          val token = authenticationResult.accessToken

          // TODO: perform request using token
      }

      override fun onError(exception: MsalException) {
          Log.d("Example", "Error: $exception")
      }

      override fun onCancel() {
          Log.d("Example", "User cancelled login")
      }
  }

  // mSingleAccountApp is our PublicClientApplication instance
  mSingleAccountApp.acquireTokenSilentAsync(scopes, authority, authCallback)

Now all that’s left to do is fill in that //TODO comment with our actual request code!

Calling the MS Graph API

To start writing request code, you’ll need to know the endpoint you’re targeting and any headers/request body details. This is when the Graph Explorer becomes really useful, because you can use it to figure out proper request formatting and response parsing!

Today, our example request will be trying to retrieve the displayName user property from the /me endpoint. From using Graph Explorer, we know that our target resource URL is https://graph.microsoft.com/v1.0/me and that we can parse the displayName directly from the response JSON.


Figure 1. After testing our desired request in Graph Explorer, we know what URL to request and what the response will look like.

Now let’s take a look at two distinct ways that the Graph API can be called using Kotlin and Android libraries. Based on the structure of your app, one approach may be easier to implement than the other.

With an HTTP library

First, we’ll try to accomplish this example request with an HTTP library. You can call the MS Graph API in an Android app like you would any other REST API. There’s a wide range of libraries available to help you set up, perform, and parse HTTP requests, but for the purposes of this post, we’ll be using Volley to match the MS Graph quickstart sample.

Using the token request skeleton from above, we can just fill in the the //TODO comment with our Volley code:

  // Build HTTP request to /me endpoint with Volley
  val queue = Volley.newRequestQueue(context)
  val graphResourceUrl = "https://graph.microsoft.com/v1.0/me"

  val stringRequest = object : JsonObjectRequest(
      Request.Method.GET,
      graphResourceUrl,
      null,
      Response.Listener { response ->
          // Parse display name from response
          val displayName = response["displayName"]
          Log.d("Example", "Response from Volley: $displayName")
      },
      Response.ErrorListener { error ->
          Log.d("Example", "Error from Volley: $error")
      }
  ) {
      // Add access token to request headers
      override fun getHeaders(): MutableMap<String, String> {
          val headers = HashMap<String, String>()
          headers["Authorization"] = "Bearer $token"
          return headers
      }
  }

  queue.add(stringRequest)

In the code snippet, you can see how to build a JSONObjectRequest with three important steps:

  • Fill in the proper request details

    • We pass in the /me resource URL and set the request method to GET
  • Add response listeners for success/error

    • On success, we parse out the displayName field directly from the JSON response
  • Add MSAL access token to request headers

    • We add the token field from our successful authentication result to the Authorization header

To learn more about how to use Volley to call the MS Graph API in Android apps, check out the quickstart sample.

With an MS Graph SDK

Next, let’s try making this same request with one of the Microsoft Graph SDKs. The MS Graph team offers SDKs for C#, PowerShell, TypeScript/JavaScript, Java, Go, PHP, and Python – today, we’ll be focusing on the MS Graph Java SDK.

To use an MS Graph SDK, there are four main steps:

  1. Install the SDK

    For our example, we’ll want to import all of the dependencies mentioned in the MS Graph Java SDK installation instructions.

  2. Set up authentication provider

    Depending on your use case, you can choose different authentication providers for the Microsoft Graph. For our example, we’ll just create a simple authentication provider that returns the access token granted by MSAL.

  3. Build graph client

    Using the authentication provider, we can then follow the instructions to create a Microsoft Graph client.

  4. Build request

    Finally, using the graph client we just built, we can then build requests and access responses!

Putting it all together, this is how we would create the same display name request with the MS Graph Java SDK:

// Build authentication provider and graph client
val authProvider = IAuthenticationProvider {
   CompletableFuture.supplyAsync { token }
}
val graphClient = GraphServiceClient.builder().authenticationProvider(authProvider).buildClient()

// Build display name request
coroutineScope.launch(Dispatchers.IO) {
    val displayName = graphClient.me().buildRequest().get()?.displayName
    Log.d("Example", "Response from MS Graph Java SDK: $displayName")
}

In the code snippet, you can see how the MS Graph Java SDK makes building the request much simpler and more readable. In fact, if we were following the approach of storing the access token after sign in, instead of re-requesting the token for every API call, then we would only require the last three lines of the code to make the request!

However, it’s also important to note that SDK requests cannot be called on the main thread, so it’s on you to make sure these requests are being handled on a background thread.

So now, you should know how to set up MSAL for an Android app, then use an MSAL token to make requests to the MS Graph API with HTTP libraries or MS Graph SDKs! We have one blog post remaining in the series, in which we’ll share a new code sample that has more complex examples of building MS Graph API requests in Android apps.

Resources and feedback

To learn more about using MS Graph in Android apps, check out:

If you have any questions, or would like to tell us about your apps, use the feedback forum or message us on Twitter @surfaceduodev.

Finally, there won’t be a livestream this week, but check out the archives on YouTube. We’ll see you online again soon!

1 comment

Discussion is closed. Login to edit/delete existing comments.

  • Ana William 0

    Thank you for the recomentation

Feedback usabilla icon