快速入门:从 Android 应用登录用户并调用 Microsoft Graph APIQuickstart: Sign in users and call the Microsoft Graph API from an Android app

本快速入门使用一个代码示例来演示 Android 应用程序如何使用 Microsoft 标识平台将工作或学校帐户登录,然后获取访问令牌并调用 Microsoft Graph API。This quickstart uses a code sample to demonstrate how an Android application can sign in work, or school accounts using the Microsoft identity platform, and then get an access token and call the Microsoft Graph API. (有关说明,请参阅示例工作原理。)(See How the sample works for an illustration.)

应用程序必须由 Azure Active Directory 中的应用对象表示,以便 Microsoft 标识平台为应用程序提供令牌。Applications must be represented by an app object in Azure Active Directory so that the Microsoft identity platform can provide tokens to your application.

为方便起见,代码示例在 AndroidManifest.xml 文件中预先配置了默认的 redirect_uri,因此你无需事先注册自己的应用对象。As a convenience, the code sample comes with a default redirect_uri preconfigured in the AndroidManifest.xml file so that you don't have to first register your own app object. redirect_uri 在一定程度上基于应用的签名密钥。A redirect_uri is partly based on your app's signing key. 示例项目中已预先配置了签名密钥,使提供的 redirect_uri 可正常工作。The sample project is preconfigured with a signing key so that the provided redirect_uri will work. 若要详细了解如何注册应用对象并将其与应用程序集成,请参阅从 Android 应用将用户登录并调用 Microsoft Graph 教程。To learn more about registering an app object and integrating it with your application, see the Sign in users and call the Microsoft Graph from an Android app tutorial.

Note

先决条件Prerequisites

  • Android StudioAndroid Studio
  • Android 16+Android 16+

步骤 1:在 Azure 门户中配置应用程序Step 1: Configure your application in the Azure portal

若要正常运行本快速入门中的代码示例,需要添加与 Auth 代理兼容的重定向 URI。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

步骤 2:下载项目Step 2: Download the project

使用 Android Studio 运行项目。Run the project using Android Studio.

步骤 3:应用已配置并可以运行Step 3: Your app is configured and ready to run

我们已经为项目配置了应用属性的值,并且该项目已准备好运行。We have configured your project with values of your app's properties and it's ready to run. 示例应用将在“单帐户模式”屏幕上启动。 The sample app starts on the Single Account Mode screen. 默认情况下,会提供默认范围 user.read,在调用 Microsoft Graph API 期间读取你自己的配置文件数据时,将使用该范围。A default scope, user.read, is provided by default, which is used when reading your own profile data during the Microsoft Graph API call. 默认提供 Microsoft Graph API 调用的 URL。The URL for the Microsoft Graph API call is provided by default. 可根据需要更改这两个默认值。You can change both of these if you wish.

显示单帐户和多帐户用法的 MSAL 示例应用

使用应用菜单可在单帐户和多帐户模式之间切换。Use the app menu to change between single and multiple account modes.

在单帐户模式下,使用工作或家庭帐户登录:In single account mode, sign in using a work or home account:

  1. 选择“以交互方式获取图形数据”,以提示用户输入其凭据。 Select Get graph data interactively to prompt the user for their credentials. 在屏幕底部可以看到调用 Microsoft Graph API 后的输出。You'll see the output from the call to the Microsoft Graph API in the bottom of the screen.
  2. 登录后,选择“以无提示方式获取图形数据”,以便在不再次提示用户输入凭据的情况下调用 Microsoft Graph API。 Once signed in, select Get graph data silently to make a call to the Microsoft Graph API without prompting the user for credentials again. 在屏幕底部可以看到调用 Microsoft Graph API 后的输出。You'll see the output from the call to the Microsoft Graph API in the bottom of the screen.

在多帐户模式下,可以重复相同的步骤。In multiple account mode, you can repeat the same steps. 此外,还可以删除登录的帐户,这也会删除该帐户的缓存令牌。Additionally, you can remove the signed-in account, which also removes the cached tokens for that account.

Note

Enter_the_Supported_Account_Info_Here

步骤 1:获取示例应用Step 1: Get the sample app

下载代码Download the code.

步骤 2:运行示例应用Step 2: Run the sample app

从 Android Studio 的“可用设备”下拉列表中选择仿真器或物理设备,然后运行应用。 Select your emulator, or physical device, from Android Studio's available devices dropdown and run the app.

示例应用将在“单帐户模式”屏幕上启动。 The sample app starts on the Single Account Mode screen. 默认情况下,会提供默认范围 user.read,在调用 Microsoft Graph API 期间读取你自己的配置文件数据时,将使用该范围。A default scope, user.read, is provided by default, which is used when reading your own profile data during the Microsoft Graph API call. 默认提供 Microsoft Graph API 调用的 URL。The URL for the Microsoft Graph API call is provided by default. 可根据需要更改这两个默认值。You can change both of these if you wish.

显示单帐户和多帐户用法的 MSAL 示例应用

使用应用菜单可在单帐户和多帐户模式之间切换。Use the app menu to change between single and multiple account modes.

在单帐户模式下,使用工作或家庭帐户登录:In single account mode, sign in using a work or home account:

  1. 选择“以交互方式获取图形数据”,以提示用户输入其凭据。 Select Get graph data interactively to prompt the user for their credentials. 在屏幕底部可以看到调用 Microsoft Graph API 后的输出。You'll see the output from the call to the Microsoft Graph API in the bottom of the screen.
  2. 登录后,选择“以无提示方式获取图形数据”,以便在不再次提示用户输入凭据的情况下调用 Microsoft Graph API。 Once signed in, select Get graph data silently to make a call to the Microsoft Graph API without prompting the user for credentials again. 在屏幕底部可以看到调用 Microsoft Graph API 后的输出。You'll see the output from the call to the Microsoft Graph API in the bottom of the screen.

在多帐户模式下,可以重复相同的步骤。In multiple account mode, you can repeat the same steps. 此外,还可以删除登录的帐户,这也会删除该帐户的缓存令牌。Additionally, you can remove the signed-in account, which also removes the cached tokens for that account.

示例工作原理How the sample works

示例应用的屏幕截图

代码已组织成多个片段,演示如何编写单帐户和多帐户 MSAL 应用。The code is organized into fragments that show how to write a single and multiple accounts MSAL app. 代码文件的组织方式如下:The code files are organized as follows:

文件File 演示Demonstrates
MainActivityMainActivity 管理 UIManages the UI
MSGraphRequestWrapperMSGraphRequestWrapper 使用 MSAL 提供的令牌调用 Microsoft Graph APICalls the Microsoft Graph API using the token provided by MSAL
MultipleAccountModeFragmentMultipleAccountModeFragment 初始化多帐户应用程序,加载用户帐户,并获取用于调用 Microsoft Graph API 的令牌Initializes a multi-account application, loads a user account, and gets a token to call the Microsoft Graph API
SingleAccountModeFragmentSingleAccountModeFragment 初始化单帐户应用程序,加载用户帐户,并获取用于调用 Microsoft Graph API 的令牌Initializes a single-account application, loads a user account, and gets a token to call the Microsoft Graph API
res/auth_config_multiple_account.jsonres/auth_config_multiple_account.json 多帐户配置文件The multiple account configuration file
res/auth_config_single_account.jsonres/auth_config_single_account.json 单帐户配置文件The single account configuration file
Gradle Scripts/build.grade (Module:app)Gradle Scripts/build.grade (Module:app) 此处添加了 MSAL 库依赖项The MSAL library dependencies are added here

现在让我们更详细地探讨这些文件,并调用每个文件中 MSAL 特定的代码。We'll now look at these files in more detail and call out the MSAL-specific code in each.

将 MSAL 添加到应用Adding MSAL to the app

MSAL (com.microsoft.identity.client) 是一个库,用于用户登录和请求令牌,此类令牌用于访问受 Microsoft 标识平台保护的 API。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. 将以下内容添加到“Gradle 脚本” > “build.gradle (Module: app)”中的“Dependencies”下时,Gradle 3.0+ 将安装该库: Gradle 3.0+ installs the library when you add the following to Gradle Scripts > build.gradle (Module: app) under Dependencies:

implementation 'com.microsoft.identity.client:msal:1.+'

可以在示例项目的 build.gradle (Module: app) 中看到以下内容:You can see this in the sample project in build.gradle (Module: app):

dependencies {
    ...
    implementation 'com.microsoft.identity.client:msal:1.+'
    ...
}

此代码指示 Gradle 从 Maven Central 下载并生成 MSAL。This instructs Gradle to download and build MSAL from maven central.

MSAL 导入MSAL imports

与 MSAL 库相关的导入为 com.microsoft.identity.client.*The imports that are relevant to the MSAL library are com.microsoft.identity.client.*. 例如,你将看到 import com.microsoft.identity.client.PublicClientApplication;,它是表示公共客户端应用程序的 PublicClientApplication 类的命名空间。For example, you'll see import com.microsoft.identity.client.PublicClientApplication; which is the namespace for the PublicClientApplication class, which represents your public client application.

SingleAccountModeFragment.javaSingleAccountModeFragment.java

此文件演示如何创建单帐户 MSAL 应用并调用 Microsoft Graph API。This file demonstrates how to create a single account MSAL app and call a Microsoft Graph API.

单帐户应用仅供单个用户使用。Single account apps are only used by a single user. 例如,你可能只使用一个帐户登录到映射应用。For example, you might just have one account that you sign into your mapping app with.

单帐户 MSAL 初始化Single account MSAL initialization

auth_config_single_account.json 中的 onCreateView() 内,单个帐户 PublicClientApplication 是使用 auth_config_single_account.json 文件中存储的配置信息创建的。In auth_config_single_account.json, in onCreateView(), a single account PublicClientApplication is created using the config information stored in the auth_config_single_account.json file. 通过以下方式初始化要在单帐户 MSAL 应用中使用的 MSAL 库:This is how you initialize the MSAL library for use in a single-account MSAL app:

...
// Creates a PublicClientApplication object with res/raw/auth_config_single_account.json
PublicClientApplication.createSingleAccountPublicClientApplication(getContext(),
        R.raw.auth_config_single_account,
        new IPublicClientApplication.ISingleAccountApplicationCreatedListener() {
            @Override
            public void onCreated(ISingleAccountPublicClientApplication application) {
                /**
                 * This test app assumes that the app is only going to support one account.
                 * This requires "account_mode" : "SINGLE" in the config json file.
                 **/
                mSingleAccountApp = application;
                loadAccount();
            }

            @Override
            public void onError(MsalException exception) {
                displayError(exception);
            }
        });

将用户登录Sign in a user

SingleAccountModeFragment.java 中,将用户登录的代码位于 signInButton 单击处理程序中的 initializeUI() 内。In SingleAccountModeFragment.java, the code to sign in a user is in initializeUI(), in the signInButton click handler.

在尝试获取令牌之前调用 signIn()Call signIn() before trying to acquire tokens. signIn() 的行为如同调用 acquireToken(),将以交互方式提示用户登录。signIn() behaves as though acquireToken() is called, resulting in an interactive prompt for the user to sign in.

将用户登录是一个异步操作。Signing in a user is an asynchronous operation. 将传递一个回调用于调用 Microsoft Graph API,并在用户登录后更新 UI:A callback is passed that calls the Microsoft Graph API and update the UI once the user signs in:

mSingleAccountApp.signIn(getActivity(), null, getScopes(), getAuthInteractiveCallback());

将用户注销Sign out a user

SingleAccountModeFragment.java 中,将用户注销的代码位于 signOutButton 单击处理程序中的 initializeUI() 内。In SingleAccountModeFragment.java, the code to sign out a user is in initializeUI(), in the signOutButton click handler. 将用户注销是一个异步操作。Signing a user out is an asynchronous operation. 将用户注销还会清除该帐户的令牌缓存。Signing the user out also clears the token cache for that account. 将用户帐户注销后,会创建一个回调来更新 UI:A callback is created to update the UI once the user account is signed out:

mSingleAccountApp.signOut(new ISingleAccountPublicClientApplication.SignOutCallback() {
    @Override
    public void onSignOut() {
        updateUI(null);
        performOperationOnSignOut();
    }

    @Override
    public void onError(@NonNull MsalException exception) {
        displayError(exception);
    }
});

以交互方式或无提示方式获取令牌Get a token interactively or silently

为了尽量减少提示用户的次数,你通常会以无提示方式获取令牌。To present the fewest number of prompts to the user, you'll typically get a token silently. 如果出错,则尝试以交互方式访问令牌。Then, if there's an error, attempt to get to token interactively. 应用首次调用 signIn() 时,它将有效充当 acquireToken() 的调用,这会提示用户提供凭据。The first time the app calls signIn(), it effectively acts as a call to acquireToken(), which will prompt the user for credentials.

在某些情况下,系统可能会提示用户选择其帐户、输入其凭据,或者许可应用请求的权限:Some situations when the user may be prompted to select their account, enter their credentials, or consent to the permissions your app has requested are:

  • 用户首次登录到应用程序The first time the user signs in to the application
  • 用户在重置其密码时需输入其凭据。If a user resets their password, they'll 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
  • 需要 MFA 或其他条件访问策略时When MFA or other Conditional Access policies are required

通过涉及用户的 UI 以交互方式获取令牌的代码位于 callGraphApiInteractiveButton 单击处理程序中的 SingleAccountModeFragment.javainitializeUI() 内:The code to get a token interactively, that is with UI that will involve the user, is in SingleAccountModeFragment.java, in initializeUI(), in the callGraphApiInteractiveButton click handler:

/**
 * If acquireTokenSilent() returns an error that requires an interaction (MsalUiRequiredException),
 * invoke acquireToken() to have the user resolve the interrupt interactively.
 *
 * Some example scenarios are
 *  - password change
 *  - the resource you're acquiring a token for has a stricter set of requirement than your Single Sign-On refresh token.
 *  - you're introducing a new scope which the user has never consented for.
 **/
mSingleAccountApp.acquireToken(getActivity(), getScopes(), getAuthInteractiveCallback());

如果用户已登录,则 acquireTokenSilentAsync() 允许应用以无提示方式请求 callGraphApiSilentButton 单击处理程序中的 initializeUI() 内显示的令牌:If the user has already signed in, acquireTokenSilentAsync() allows apps to request tokens silently as shown in initializeUI(), in the callGraphApiSilentButton click handler:

/**
 * Once you've signed the user in,
 * you can perform acquireTokenSilent to obtain resources without interrupting the user.
 **/
  mSingleAccountApp.acquireTokenSilentAsync(getScopes(), AUTHORITY, getAuthSilentCallback());

加载帐户Load an account

用于加载帐户的代码位于 SingleAccountModeFragment.java 中的 loadAccount() 内。The code to load an account is in SingleAccountModeFragment.java in loadAccount(). 加载用户帐户是一个异步操作,因此,在帐户加载、更改或出错时要处理的回调将传递到 MSAL。Loading the user's account is an asynchronous operation, so callbacks to handle when the account loads, changes, or an error occurs is passed to MSAL. 以下代码也会处理在删除了帐户、用户切换到其他帐户等情况时发生的 onAccountChanged()The following code also handles onAccountChanged(), which occurs when an account is removed, the user changes to another account, and so on.

private void loadAccount() {
    ...

    mSingleAccountApp.getCurrentAccountAsync(new ISingleAccountPublicClientApplication.CurrentAccountCallback() {
        @Override
        public void onAccountLoaded(@Nullable IAccount activeAccount) {
            // You can use the account data to update your UI or your app database.
            updateUI(activeAccount);
        }

        @Override
        public void onAccountChanged(@Nullable IAccount priorAccount, @Nullable IAccount currentAccount) {
            if (currentAccount == null) {
                // Perform a cleanup task as the signed-in account changed.
                performOperationOnSignOut();
            }
        }

        @Override
        public void onError(@NonNull MsalException exception) {
            displayError(exception);
        }
    });

调用 Microsoft GraphCall Microsoft Graph

用户登录后,将通过 SingleAccountModeFragment.java 中定义的 callGraphAPI() 的 HTTP 请求调用 Microsoft Graph。When a user is signed in, the call to Microsoft Graph is made via an HTTP request by callGraphAPI() which is defined in SingleAccountModeFragment.java. 此函数是一个简化示例的包装器,它会执行从 authenticationResult 获取访问令牌等某些任务,打包 MSGraphRequestWrapper 的调用,并显示调用结果。This function is a wrapper that simplifies the sample by doing some tasks such as getting the access token from the authenticationResult and packaging the call to the MSGraphRequestWrapper, and displaying the results of the call.

private void callGraphAPI(final IAuthenticationResult authenticationResult) {
    MSGraphRequestWrapper.callGraphAPIUsingVolley(
            getContext(),
            graphResourceTextView.getText().toString(),
            authenticationResult.getAccessToken(),
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    /* Successfully called graph, process data and send to UI */
                    ...
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    ...
                }
            });
}

auth_config_single_account.jsonauth_config_single_account.json

这是使用单个帐户的 MSAL 应用的配置文件。This is the configuration file for a MSAL app that uses a single account.

有关这些字段的说明,请参阅了解 Android MSAL 配置文件See Understand the Android MSAL configuration file for an explanation of these fields.

请注意 "account_mode" : "SINGLE",它会将此应用配置为使用单个帐户。Note the presence of "account_mode" : "SINGLE", which configures this app to use a single account.

"client_id" 已预配置为使用 Microsoft 维护的应用对象注册。"client_id" is preconfigured to use an app object registration that Microsoft maintains. "redirect_uri" 已预配置为使用代码示例随附的签名密钥。"redirect_uri"is preconfigured to use the signing key provided with the code sample.

{
  "client_id" : "0984a7b6-bc13-4141-8b0d-8f767e136bb7",
  "authorization_user_agent" : "DEFAULT",
  "redirect_uri" : "msauth://com.azuresamples.msalandroidapp/1wIqXSqBj7w%2Bh11ZifsnqwgyKrY%3D",
  "account_mode" : "SINGLE",
  "broker_redirect_uri_registered": true,
  "authorities" : [
    {
      "type": "AAD",
      "audience": {
        "type": "AzureADMultipleOrgs",
        "tenant_id": "common"
      }
    }
  ]
}

MultipleAccountModeFragment.javaMultipleAccountModeFragment.java

此文件演示如何创建多帐户 MSAL 应用并调用 Microsoft Graph API。This file demonstrates how to create a multiple account MSAL app and call a Microsoft Graph API.

邮件应用就是多帐户应用的一个例子,它允许使用多个用户帐户,例如工作帐户。An example of a multiple account app is a mail app that allows you to work with multiple user accounts such as a work account.

多帐户 MSAL 初始化Multiple account MSAL initialization

MultipleAccountModeFragment.java 文件中的 onCreateView() 内,多帐户应用对象 (IMultipleAccountPublicClientApplication) 是使用 auth_config_multiple_account.json file 中存储的配置信息创建的:In the MultipleAccountModeFragment.java file, in onCreateView(), a multiple account app object (IMultipleAccountPublicClientApplication) is created using the config information stored in the auth_config_multiple_account.json file:

// Creates a PublicClientApplication object with res/raw/auth_config_multiple_account.json
PublicClientApplication.createMultipleAccountPublicClientApplication(getContext(),
        R.raw.auth_config_multiple_account,
        new IPublicClientApplication.IMultipleAccountApplicationCreatedListener() {
            @Override
            public void onCreated(IMultipleAccountPublicClientApplication application) {
                mMultipleAccountApp = application;
                loadAccounts();
            }

            @Override
            public void onError(MsalException exception) {
                ...
            }
        });

创建的 MultipleAccountPublicClientApplication 对象存储在某个类成员变量中,因此可以使用该对象来与 MSAL 库交互,以获取令牌以及加载和删除用户帐户。The created MultipleAccountPublicClientApplication object is stored in a class member variable so that it can be used to interact with the MSAL library to acquire tokens and load and remove the user account.

加载帐户Load an account

多帐户应用通常调用 getAccounts() 来选择要用于 MSAL 操作的帐户。Multiple account apps usually call getAccounts() to select the account to use for MSAL operations. 用于加载帐户的代码位于 MultipleAccountModeFragment.java 文件中的 loadAccounts() 内。The code to load an account is in the MultipleAccountModeFragment.java file, in loadAccounts(). 加载用户帐户是一个异步操作。Loading the user's account is an asynchronous operation. 因此,某个回调会处理帐户已加载、更改或出错时的情况。So a callback handles the situations when the account is loaded, changes, or an error occurs.

/**
 * Load currently signed-in accounts, if there's any.
 **/
private void loadAccounts() {
    if (mMultipleAccountApp == null) {
        return;
    }

    mMultipleAccountApp.getAccounts(new IPublicClientApplication.LoadAccountsCallback() {
        @Override
        public void onTaskCompleted(final List<IAccount> result) {
            // You can use the account data to update your UI or your app database.
            accountList = result;
            updateUI(accountList);
        }

        @Override
        public void onError(MsalException exception) {
            displayError(exception);
        }
    });
}

以交互方式或无提示方式获取令牌Get a token interactively or silently

在某些情况下,系统可能会提示用户选择其帐户、输入其凭据,或者许可应用请求的权限:Some situations when the user may be prompted to select their account, enter their credentials, or consent to the permissions your app has requested are:

  • 用户首次登录应用程序The first time users sign in to the application
  • 用户在重置其密码时需输入其凭据。If a user resets their password, they'll 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
  • 需要 MFA 或其他条件访问策略时When MFA or other Conditional Access policies are required

多帐户应用通常使用 acquireToken() 调用通过涉及用户的 UI 以交互方式获取令牌。Multiple account apps should typically acquire tokens interactively, that is with UI that involves the user, with a call to acquireToken(). 以交互方式获取令牌的代码位于 callGraphApiInteractiveButton 单击处理程序中的 MultipleAccountModeFragment.java 文件的 initializeUI() 内:The code to get a token interactively is in the MultipleAccountModeFragment.java file in initializeUI(), in the callGraphApiInteractiveButton click handler:

/**
 * Acquire token interactively. It will also create an account object for the silent call as a result (to be obtained by getAccount()).
 *
 * If acquireTokenSilent() returns an error that requires an interaction,
 * invoke acquireToken() to have the user resolve the interrupt interactively.
 *
 * Some example scenarios are
 *  - password change
 *  - the resource you're acquiring a token for has a stricter set of requirement than your SSO refresh token.
 *  - you're introducing a new scope which the user has never consented for.
 **/
mMultipleAccountApp.acquireToken(getActivity(), getScopes(), getAuthInteractiveCallback());

应用不应该在用户每次请求令牌时都要求他们登录。Apps shouldn't require the user to sign in every time they request a token. 如果用户已登录,则 acquireTokenSilentAsync() 允许应用以无提示方式请求令牌,如 callGraphApiSilentButton 单击处理程序的 MultipleAccountModeFragment.java 文件的 initializeUI() 中所示:If the user has already signed in, acquireTokenSilentAsync() allows apps to request tokens without prompting the user, as shown in the MultipleAccountModeFragment.java file, ininitializeUI() in the callGraphApiSilentButton click handler:

/**
 * Performs acquireToken without interrupting the user.
 *
 * This requires an account object of the account you're obtaining a token for.
 * (can be obtained via getAccount()).
 */
mMultipleAccountApp.acquireTokenSilentAsync(getScopes(),
    accountList.get(accountListSpinner.getSelectedItemPosition()),
    AUTHORITY,
    getAuthSilentCallback());

删除帐户Remove an account

用于删除帐户以及该帐户的所有已缓存令牌的代码位于“删除帐户”按钮的处理程序的 MultipleAccountModeFragment.java 文件中的 initializeUI() 内。The code to remove an account, and any cached tokens for the account, is in the MultipleAccountModeFragment.java file in initializeUI() in the handler for the remove account button. 在删除帐户之前,需要提供从 getAccounts()acquireToken() 等 MSAL 方法获取的帐户对象。Before you can remove an account, you need an account object, which you obtain from MSAL methods like getAccounts() and acquireToken(). 由于删除帐户是一个异步操作,因此需提供 onRemoved 回调来更新 UI。Because removing an account is an asynchronous operation, the onRemoved callback is supplied to update the UI.

/**
 * Removes the selected account and cached tokens from this app (or device, if the device is in shared mode).
 **/
mMultipleAccountApp.removeAccount(accountList.get(accountListSpinner.getSelectedItemPosition()),
        new IMultipleAccountPublicClientApplication.RemoveAccountCallback() {
            @Override
            public void onRemoved() {
                ...
                /* Reload account asynchronously to get the up-to-date list. */
                loadAccounts();
            }

            @Override
            public void onError(@NonNull MsalException exception) {
                displayError(exception);
            }
        });

auth_config_multiple_account.jsonauth_config_multiple_account.json

这是使用多个帐户的 MSAL 应用的配置文件。This is the configuration file for a MSAL app that uses multiple accounts.

有关各个字段的说明,请参阅了解 Android MSAL 配置文件See Understand the Android MSAL configuration file for an explanation of the various fields.

auth_config_single_account.json 配置文件不同,此配置文件包含 "account_mode" : "MULTIPLE" 而不是 "account_mode" : "SINGLE",因为这是一个多帐户应用。Unlike the auth_config_single_account.json configuration file, this config file has "account_mode" : "MULTIPLE" instead of "account_mode" : "SINGLE" because this is a multiple account app.

"client_id" 已预配置为使用 Microsoft 维护的应用对象注册。"client_id" is preconfigured to use an app object registration that Microsoft maintains. "redirect_uri" 已预配置为使用代码示例随附的签名密钥。"redirect_uri"is preconfigured to use the signing key provided with the code sample.

{
  "client_id" : "0984a7b6-bc13-4141-8b0d-8f767e136bb7",
  "authorization_user_agent" : "DEFAULT",
  "redirect_uri" : "msauth://com.azuresamples.msalandroidapp/1wIqXSqBj7w%2Bh11ZifsnqwgyKrY%3D",
  "account_mode" : "MULTIPLE",
  "broker_redirect_uri_registered": true,
  "authorities" : [
    {
      "type": "AAD",
      "audience": {
        "type": "AzureADMultipleOrgs",
        "tenant_id": "common"
      }
    }
  ]
}

后续步骤Next steps

了解创建本快速入门中使用的应用程序的步骤Learn the steps to create the application used in this quickstart

尝试学习从 Android 应用将用户登录并调用 Microsoft Graph 教程,其中逐步介绍了如何生成一个可以获取访问令牌,并使用该令牌调用 Microsoft Graph API 的 Android 应用。Try out the Sign in users and call the Microsoft Graph from an Android app tutorial for a step-by-step guide for building an Android app that gets an access token and uses it to call the Microsoft Graph API.

适用于 Android 库 wiki 的 MSALMSAL for Android library wiki

阅读有关适用于 Android 的 MSAL 库的详细信息: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: