Sign in users and call an API in a sample Android mobile app by using native authentication

This article demonstrates how to configure a sample Android mobile application to call an ASP.NET Core web API.

Prerequisites

Register a web API application

  1. Sign in to the Microsoft Entra admin center as at least an Application Developer.

  2. If you have access to multiple tenants, use the Settings icon in the top menu to switch to your external tenant from the Directories + subscriptions menu.

  3. Browse to Identity > Applications > App registrations.

  4. Select + New registration.

  5. In the Register an application page that appears, enter your application's registration information:

    1. In the Name section, enter a meaningful application name that will be displayed to users of the app, for example ciam-ToDoList-api.

    2. Under Supported account types, select Accounts in this organizational directory only.

  6. Select Register to create the application.

  7. The application's Overview pane is displayed when registration is complete. Record the Directory (tenant) ID and the Application (client) ID to be used in your application source code.

Configure API scopes

An API needs to publish a minimum of one scope, also called Delegated Permission, for the client apps to obtain an access token for a user successfully. To publish a scope, follow these steps:

  1. From the App registrations page, select the API application that you created (ciam-ToDoList-api) to open its Overview page.

  2. Under Manage, select Expose an API.

  3. At the top of the page, next to Application ID URI, select the Add link to generate a URI that is unique for this app.

  4. Accept the proposed Application ID URI such as api://{clientId}, and select Save. When your web application requests an access token for the web API, it adds the URI as the prefix for each scope that you define for the API.

  5. Under Scopes defined by this API, select Add a scope.

  6. Enter the following values that define a read access to the API, then select Add scope to save your changes:

    Property Value
    Scope name ToDoList.Read
    Who can consent Admins only
    Admin consent display name Read users ToDo list using the 'TodoListApi'
    Admin consent description Allow the app to read the user's ToDo list using the 'TodoListApi'.
    State Enabled
  7. Select Add a scope again, and enter the following values that define a read and write access scope to the API. Select Add scope to save your changes:

    Property Value
    Scope name ToDoList.ReadWrite
    Who can consent Admins only
    Admin consent display name Read and write users ToDo list using the 'ToDoListApi'
    Admin consent description Allow the app to read and write the user's ToDo list using the 'ToDoListApi'
    State Enabled
  8. Under Manage, select Manifest to open the API manifest editor.

  9. Set accessTokenAcceptedVersion property to 2.

  10. Select Save.

Learn more about the principle of least privilege when publishing permissions for a web API.

Configure app roles

An API needs to publish a minimum of one app role for applications, also called Application Permission, for the client apps to obtain an access token as themselves. Application permissions are the type of permissions that APIs should publish when they want to enable client applications to successfully authenticate as themselves and not need to sign-in users. To publish an application permission, follow these steps:

  1. From the App registrations page, select the application that you created (such as ciam-ToDoList-api) to open its Overview page.

  2. Under Manage, select App roles.

  3. Select Create app role, then enter the following values, then select Apply to save your changes:

    Property Value
    Display name ToDoList.Read.All
    Allowed member types Applications
    Value ToDoList.Read.All
    Description Allow the app to read every user's ToDo list using the 'TodoListApi'
  4. Select Create app role again, then enter the following values for the second app role, then select Apply to save your changes:

    Property Value
    Display name ToDoList.ReadWrite.All
    Allowed member types Applications
    Value ToDoList.ReadWrite.All
    Description Allow the app to read and write every user's ToDo list using the 'ToDoListApi'

Configure optional claims

Tokens returned by Microsoft identity are kept smaller to ensure optimal performance by clients that request them. As a result, several claims are no longer present in the token by default and must be asked for specifically on a per-application basis. For this app, you include idtyp optional claim to help the web API to determine if a token is an app token or an app+user token. Although you can use a combination of scp and roles claims for the same purpose, the use of the idtyp claim is the easiest way to tell an app token and an app+user token apart. For example, the value of this claim is app when the token is an app-only token.

Use the following steps to configure idtyp optional claim:

  1. From the App registrations page, for which you want to configure optional claim, such as ciam-client-app, to open its Overview page.

  2. Under Manage, select Token configuration.

  3. Select Add optional claim.

  4. Under Token type, choose Access.

  5. Select the optional claim idtyp.

  6. Select Add to save your changes.

Grant API permissions to the Android sample app

Once you've registered both your client app and web API and you've exposed the API by creating scopes, you can configure the client's permissions to the API by following these steps:

  1. From the App registrations page, select the application that you created (such as ciam-client-app) to open its Overview page.

  2. Under Manage, select API permissions.

  3. Under Configured permissions, select Add a permission.

  4. Select the APIs my organization uses tab.

  5. In the list of APIs, select the API such as ciam-ToDoList-api.

  6. Select Delegated permissions option.

  7. From the permissions list, select ToDoList.Read, ToDoList.ReadWrite (use the search box if necessary).

  8. Select the Add permissions button.

  9. At this point, you've assigned the permissions correctly. However, since the tenant is a customer's tenant, the consumer users themselves can't consent to these permissions. To address this, you as the admin must consent to these permissions on behalf of all the users in the tenant:

    1. Select Grant admin consent for <your tenant name>, then select Yes.

    2. Select Refresh, then verify that Granted for <your tenant name> appears under Status for both permissions.

  10. From the Configured permissions list, select the ToDoList.Read and ToDoList.ReadWrite permissions, one at a time, and then copy the permission's full URI for later use. The full permission URI looks something similar to api://{clientId}/{ToDoList.Read} or api://{clientId}/{ToDoList.ReadWrite}.

Clone or download sample web API

To obtain the sample application, you can either clone it from GitHub or download it as a .zip file.

  • To clone the sample, open a command prompt and navigate to where you wish to create the project, and enter the following command:

    git clone https://github.com/Azure-Samples/ms-identity-ciam-dotnet-tutorial.git
    
  • Download the .zip file. Extract it to a file path where the length of the name is fewer than 260 characters.

Configure and run sample web API

  1. In your code editor, open 2-Authorization/1-call-own-api-aspnet-core-mvc/ToDoListAPI/appsettings.json file.

  2. Find the placeholder:

    • Enter_the_Application_Id_Here and replace it with the Application (client) ID of the web API you copied earlier.
    • Enter_the_Tenant_Id_Here and replace it with the Directory (tenant) ID you copied earlier.
    • Enter_the_Tenant_Subdomain_Here and replace it with the Directory (tenant) subdomain. For example, if your tenant primary domain is contoso.onmicrosoft.com, use contoso. If you don't have your tenant name, learn how to read your tenant details.

You need to host your web API for the Android sample app to call it. Follow Quickstart: Deploy an ASP.NET web app to deploy your web API.

Configure sample Android mobile app to call web API

  1. In your Android Studio, open /app/src/main/java/com/azuresamples/msalnativeauthandroidkotlinsampleapp/AccessApiFragment.kt file.

  2. Find property named WEB_API_BASE_URL and set the URL to your web API.

    private const val WEB_API_BASE_URL = "" // Developers should set the respective URL of their web API here
    
  3. Find property named scopes and set the scopes recorded in Grant API permissions to the Android sample app.

    private val scopes = listOf<String>() // Developers should set the respective scopes of their web API here. For example, private val scopes = listOf<String>("api://{clientId}/{ToDoList.Read}", "api://{clientId}/{ToDoList.ReadWrite}")
    

Run Android sample app and call web API

To build and run your app, follow these steps:

  1. In the toolbar, select your app from the run configurations menu.

  2. In the target device menu, select the device that you want to run your app on.

    If you don't have any devices configured, you need to either create an Android Virtual Device to use the Android Emulator or connect a physical device.

  3. Select Run button. The app opens on the email and one-time passcode screen.

  4. Select the API tab to test the API call. A successful call to the web API returns HTTP 200, while HTTP 403 signifies unauthorized access.

Next steps