Schnellstart: Benutzeranmeldung und Aufrufen der Microsoft Graph-API aus einer Android-AppQuickstart: Sign in users and call the Microsoft Graph API from an Android app
In diesem Schnellstart laden Sie ein Codebeispiel herunter und führen es aus, das zeigt, wie eine Android-Anwendung Benutzer anmelden und ein Zugriffstoken abrufen kann, um die Microsoft Graph-API aufzurufen.In this quickstart, you download and run a code sample that demonstrates how an Android application can sign in users and get an access token to call the Microsoft Graph API.
Eine Abbildung finden Sie unter Funktionsweise des Beispiels.See How the sample works for an illustration.
Anwendungen müssen durch ein App-Objekt in Azure Active Directory dargestellt werden, damit Microsoft Identity Platform Token für Ihre Anwendung bereitstellen kann.Applications must be represented by an app object in Azure Active Directory so that the Microsoft identity platform can provide tokens to your application.
VoraussetzungenPrerequisites
- Ein Azure-Konto mit einem aktiven Abonnement.An Azure account with an active subscription. Sie können kostenlos ein Konto erstellen.Create an account for free.
- Android StudioAndroid Studio
- Android 16+Android 16+
Schritt 1: Konfigurieren Ihrer Anwendung im Azure-PortalStep 1: Configure your application in the Azure portal
Damit das Codebeispiel für diese Schnellstartanleitung funktioniert, müssen Sie einen mit dem Authentifizierungsbroker kompatiblen Umleitungs-URI hinzufügen.For the code sample for this quickstart to work, you need to add a redirect URI compatible with the Auth broker.
Make these changes for me (Diese Änderungen für mich vornehmen)Make these changes for me
: Ihre Anwendung ist mit diesen Attributen konfiguriert.
Your application is configured with these attributes
Schritt 2: Herunterladen des ProjektsStep 2: Download the project
Führen Sie das Projekt mit Android Studio aus.Run the project using Android Studio.
Schritt 3: Ihre App ist konfiguriert und betriebsbereitStep 3: Your app is configured and ready to run
Wir haben das Projekt mit Werten Ihrer App-Eigenschaften konfiguriert. Es ist nun ausführungsbereit.We have configured your project with values of your app's properties and it's ready to run. Die Beispiel-App wird auf dem Bildschirm Single Account Mode (Einzelkontomodus) gestartet.The sample app starts on the Single Account Mode screen. Standardmäßig wird der Standardbereich user.read angegeben. Dieser wird beim Lesen Ihrer eigenen Profildaten während des Aufrufs der Microsoft Graph-API verwendet.A default scope, user.read, is provided by default, which is used when reading your own profile data during the Microsoft Graph API call. Die URL für die Microsoft Graph-API wird standardmäßig bereitgestellt.The URL for the Microsoft Graph API call is provided by default. Sie können beide Werte ggf. ändern.You can change both of these if you wish.
Verwenden Sie das App-Menü, um zwischen dem Einzelkontomodus und dem Modus für mehrere Konten zu wechseln.Use the app menu to change between single and multiple account modes.
Melden Sie sich im Einzelkontomodus mit einem Home- oder Geschäftskonto oder an:In single account mode, sign in using a work or home account:
- Wählen Sie Get graph data interactively (Graph-Daten interaktiv abrufen) aus, um Benutzer nach ihren Anmeldeinformationen abzufragen.Select Get graph data interactively to prompt the user for their credentials. Die Ausgabe des Aufrufs der Microsoft Graph-API wird im Bildschirm unten angezeigt.You'll see the output from the call to the Microsoft Graph API in the bottom of the screen.
- Wählen Sie nach der Anmeldung Get graph data silently (Graph-Daten im Hintergrund abrufen) aus, um die Microsoft Graph-API erneut aufzurufen, ohne dass die Anmeldeinformationen des Benutzers erneut abgefragt werden.Once signed in, select Get graph data silently to make a call to the Microsoft Graph API without prompting the user for credentials again. Die Ausgabe des Aufrufs der Microsoft Graph-API wird im Bildschirm unten angezeigt.You'll see the output from the call to the Microsoft Graph API in the bottom of the screen.
Im Modus für mehrere Konten können Sie dieselben Schritte ausführen.In multiple account mode, you can repeat the same steps. Außerdem können Sie das angemeldete Konto entfernen. Dadurch werden auch die zwischengespeicherten Token für dieses Konto entfernt.Additionally, you can remove the signed-in account, which also removes the cached tokens for that account.
Hinweis
Enter_the_Supported_Account_Info_Here
Schritt 1: Abrufen der Beispiel-AppStep 1: Get the sample app
Laden Sie den Code herunter.Download the code.
Schritt 2: Ausführen der Beispiel-AppStep 2: Run the sample app
Wählen Sie in der Dropdownliste Verfügbare Geräte von Android Studio Ihren Emulator oder Ihr physisches Gerät aus, und führen Sie die App aus.Select your emulator, or physical device, from Android Studio's available devices dropdown and run the app.
Die Beispiel-App wird auf dem Bildschirm Single Account Mode (Einzelkontomodus) gestartet.The sample app starts on the Single Account Mode screen. Standardmäßig wird der Standardbereich user.read angegeben. Dieser wird beim Lesen Ihrer eigenen Profildaten während des Aufrufs der Microsoft Graph-API verwendet.A default scope, user.read, is provided by default, which is used when reading your own profile data during the Microsoft Graph API call. Die URL für die Microsoft Graph-API wird standardmäßig bereitgestellt.The URL for the Microsoft Graph API call is provided by default. Sie können beide Werte ggf. ändern.You can change both of these if you wish.
Verwenden Sie das App-Menü, um zwischen dem Einzelkontomodus und dem Modus für mehrere Konten zu wechseln.Use the app menu to change between single and multiple account modes.
Melden Sie sich im Einzelkontomodus mit einem Home- oder Geschäftskonto oder an:In single account mode, sign in using a work or home account:
- Wählen Sie Get graph data interactively (Graph-Daten interaktiv abrufen) aus, um Benutzer nach ihren Anmeldeinformationen abzufragen.Select Get graph data interactively to prompt the user for their credentials. Die Ausgabe des Aufrufs der Microsoft Graph-API wird im Bildschirm unten angezeigt.You'll see the output from the call to the Microsoft Graph API in the bottom of the screen.
- Wählen Sie nach der Anmeldung Get graph data silently (Graph-Daten im Hintergrund abrufen) aus, um die Microsoft Graph-API erneut aufzurufen, ohne dass die Anmeldeinformationen des Benutzers erneut abgefragt werden.Once signed in, select Get graph data silently to make a call to the Microsoft Graph API without prompting the user for credentials again. Die Ausgabe des Aufrufs der Microsoft Graph-API wird im Bildschirm unten angezeigt.You'll see the output from the call to the Microsoft Graph API in the bottom of the screen.
Im Modus für mehrere Konten können Sie dieselben Schritte ausführen.In multiple account mode, you can repeat the same steps. Außerdem können Sie das angemeldete Konto entfernen. Dadurch werden auch die zwischengespeicherten Token für dieses Konto entfernt.Additionally, you can remove the signed-in account, which also removes the cached tokens for that account.
Funktionsweise des BeispielsHow the sample works
Der Code ist in Fragmente unterteilt, in denen veranschaulicht wird, wie Sie eine MSAL-App für ein einzelnes Konto und für mehrere Konten schreiben.The code is organized into fragments that show how to write a single and multiple accounts MSAL app. Die Codedateien sind wie folgt organisiert:The code files are organized as follows:
DateiFile | ZeigtDemonstrates |
---|---|
MainActivityMainActivity | Verwaltet die BenutzeroberflächeManages the UI |
MSGraphRequestWrapperMSGraphRequestWrapper | Ruft die Microsoft Graph-API mit dem von MSAL bereitgestellten Token aufCalls the Microsoft Graph API using the token provided by MSAL |
MultipleAccountModeFragmentMultipleAccountModeFragment | Initialisiert eine Anwendung für mehrere Konten, lädt ein Benutzerkonto und ruft ein Token für den Aufruf der Microsoft Graph-API abInitializes a multi-account application, loads a user account, and gets a token to call the Microsoft Graph API |
SingleAccountModeFragmentSingleAccountModeFragment | Initialisiert eine Anwendung für ein einzelnes Konto, lädt ein Benutzerkonto und ruft ein Token für den Aufruf der Microsoft Graph-API abInitializes 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 | Die Konfigurationsdatei für mehrere KontenThe multiple account configuration file |
res/auth_config_single_account.jsonres/auth_config_single_account.json | Die Konfigurationsdatei für ein KontoThe single account configuration file |
Gradle Scripts/build.grade (Module:app)Gradle Scripts/build.grade (Module:app) | Die Abhängigkeiten der MSAL-Bibliothek werden hier hinzugefügtThe MSAL library dependencies are added here |
Diese Dateien werden nun ausführlicher betrachtet, und der MSAL-spezifische Code in jeder wird hervorgehoben.We'll now look at these files in more detail and call out the MSAL-specific code in each.
Hinzufügen von MSAL zur AppAdding MSAL to the app
MSAL (com.microsoft.identity.client) ist die Bibliothek zum Anmelden von Benutzern und Anfordern von Token, die für den Zugriff auf eine durch Microsoft Identity Platform geschützte API verwendet wird.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 3.0+ installiert die Bibliothek, wenn Gradle Scripts > build.gradle (Module: app) unter Dependencies folgenden Code hinzufügen: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:2.+'
Dies wird im Beispielprojekt in build.gradle (Module: app) veranschaulicht:You can see this in the sample project in build.gradle (Module: app):
dependencies {
...
implementation 'com.microsoft.identity.client:msal:2.+'
...
}
Dadurch wird Gradle angewiesen, MSAL von Maven Central herunterzuladen und zu kompilieren.This instructs Gradle to download and build MSAL from maven central.
MSAL-ImporteMSAL imports
Die relevanten Importe für die MSAL-Bibliothek sind com.microsoft.identity.client.*
.The imports that are relevant to the MSAL library are com.microsoft.identity.client.*
. So wird beispielsweise import com.microsoft.identity.client.PublicClientApplication;
angezeigt. Dies ist der Namespace für die PublicClientApplication
-Klasse, die Ihre öffentliche Clientanwendung darstellt.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
Diese Datei veranschaulicht, wie Sie eine Einzelkonto-MSAL-App erstellen und eine Microsoft Graph-API aufrufen.This file demonstrates how to create a single account MSAL app and call a Microsoft Graph API.
Einzelkonto-Apps werden nur von einem einzigen Benutzer verwendet.Single account apps are only used by a single user. Sie verfügen beispielsweise nur über ein Konto, mit dem Sie sich bei ihrer Mapping-App anmelden.For example, you might just have one account that you sign into your mapping app with.
Einzelkonto-MSAL-InitialisierungSingle account MSAL initialization
In auth_config_single_account.json
wird in onCreateView()
eine Einzelkonto-PublicClientApplication
mit den in der Datei auth_config_single_account.json
gespeicherten Konfigurationsinformationen erstellt.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. So initialisieren Sie die MSAL-Bibliothek für die Verwendung in einer Einzelkonto-MSAL-App: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);
}
});
Anmelden eines BenutzersSign in a user
In SingleAccountModeFragment.java
befindet sich der Code zum Anmelden eines Benutzers in initializeUI()
im signInButton
-Click-Handler.In SingleAccountModeFragment.java
, the code to sign in a user is in initializeUI()
, in the signInButton
click handler.
Rufen Sie signIn()
auf, bevor Sie versuchen, Token abzurufen.Call signIn()
before trying to acquire tokens. signIn()
verhält sich wie bei einem Aufruf von acquireToken()
. Dadurch wird eine interaktive Anmeldeaufforderung für den Benutzer erhalten.signIn()
behaves as though acquireToken()
is called, resulting in an interactive prompt for the user to sign in.
Das Anmelden eines Benutzers ist ein asynchroner Vorgang.Signing in a user is an asynchronous operation. Es wird ein Rückruf übergeben, der die Microsoft Graph-API aufruft und bei Anmeldung des Benutzers die Benutzeroberfläche aktualisiert: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());
Abmelden eines BenutzersSign out a user
In SingleAccountModeFragment.java
befindet sich der Code zum Abmelden eines Benutzers in initializeUI()
im signOutButton
-Click-Handler.In SingleAccountModeFragment.java
, the code to sign out a user is in initializeUI()
, in the signOutButton
click handler. Das Abmelden eines Benutzers ist ein asynchroner Vorgang.Signing a user out is an asynchronous operation. Durch das Abmelden des Benutzers wird auch der Tokencache für das betreffende Konto gelöscht.Signing the user out also clears the token cache for that account. Es wird ein Rückruf erstellt, mit dem die Benutzeroberfläche aktualisiert wird, sobald das Benutzerkonto abgemeldet wurde: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);
}
});
Interaktives Abrufen eines Tokens oder Abrufen eines Tokens im HintergrundGet a token interactively or silently
Um dem Benutzer eine möglichst geringe Anzahl von Eingabeaufforderungen zu präsentieren, wird ein Token im Allgemeinen im Hintergrund abgerufen.To present the fewest number of prompts to the user, you'll typically get a token silently. Sollte dabei ein Fehler auftreten, wird versucht, das Token interaktiv abzurufen.Then, if there's an error, attempt to get to token interactively. Der erste Aufruf von signIn()
durch die App fungiert als Aufruf von acquireToken()
, durch den der Benutzer nach Anmeldeinformationen abgefragt wird.The first time the app calls signIn()
, it effectively acts as a call to acquireToken()
, which will prompt the user for credentials.
Es gibt einige Situationen, in denen der Benutzer aufgefordert werden kann, sein Konto auszuwählen, seine Anmeldeinformationen einzugeben oder den von der App angeforderten Berechtigungen zuzustimmen: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:
- Wenn sich der Benutzer erstmalig bei der Anwendung anmeldetThe first time the user signs in to the application
- Wenn ein Benutzer sein Kennwort zurücksetzt, muss er seine Anmeldeinformationen eingeben.If a user resets their password, they'll need to enter their credentials
- Wenn die Zustimmung widerrufen wurdeIf consent is revoked
- Wenn die App explizit eine Zustimmung erfordertIf your app explicitly requires consent
- Wenn Ihre Anwendung zum ersten Mal Zugriff auf eine Ressource anfordertWhen your application is requesting access to a resource for the first time
- Wenn MFA oder andere Richtlinien für bedingten Zugriff erforderlich sindWhen MFA or other Conditional Access policies are required
Der Code zum interaktiven Abrufen eines Tokens (d. h. über die Benutzeroberfläche, in welcher der Benutzer Aktionen ausführen muss) befindet sich in SingleAccountModeFragment.java
in initializeUI()
im callGraphApiInteractiveButton
-Click-Handler: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());
Wenn sich der Benutzer bereits angemeldet hat, gestattet acquireTokenSilentAsync()
Apps das Anfordern von Token im Hintergrund. Dies wird in initializeUI()
im callGraphApiSilentButton
-Click-Handler gezeigt: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());
Laden eines KontosLoad an account
Der Code zum Laden eines Kontos befindet sich in SingleAccountModeFragment.java
in loadAccount()
.The code to load an account is in SingleAccountModeFragment.java
in loadAccount()
. Das Laden des Benutzerkontos ist ein asynchroner Vorgang, daher werden Rückrufe für die Verarbeitung beim Laden oder Wechseln des Kontos oder bei auftretenden Fehlern an MSAL übergeben.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. Im folgenden Code wird außerdem onAccountChanged()
behandelt; dies tritt auf, wenn ein Konto entfernt wird, der Benutzer zu einem anderen Konto wechselt usw.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);
}
});
Aufrufen von Microsoft GraphCall Microsoft Graph
Wenn ein Benutzer angemeldet ist, wird der Aufruf von Microsoft Graph über eine HTTP-Anforderung durch callGraphAPI()
gemäß der Definition in SingleAccountModeFragment.java
ausgeführt.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
. Diese Funktion ist ein Wrapper. Dieser vereinfacht das Beispiel, indem einige Aufgaben wie Abrufen des Zugriffstokens vom authenticationResult
, Verpacken des Aufrufs in den MSGraphRequestWrapper und Anzeigen der Ergebnisse des Aufrufs ausgeführt werden.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
Dies ist die Konfigurationsdatei für eine MSAL-App, die ein einziges Konto verwendet.This is the configuration file for a MSAL app that uses a single account.
Eine Erläuterung dieser Felder finden Sie unter Android-MSAL-Konfigurationsdatei.See Understand the Android MSAL configuration file for an explanation of these fields.
Beachten Sie, dass "account_mode" : "SINGLE"
vorhanden ist; hierdurch wird diese App für die Verwendung eines einzigen Kontos konfigurieren.Note the presence of "account_mode" : "SINGLE"
, which configures this app to use a single account.
"client_id"
ist für die Verwendung einer App-Objekt-Registrierung vorkonfiguriert, die von Microsoft verwaltet wird."client_id"
is preconfigured to use an app object registration that Microsoft maintains.
"redirect_uri"
ist so vorkonfiguriert, dass der Signaturschlüssel aus dem Codebeispiel verwendet wird."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": "AzureADandPersonalMicrosoftAccount",
"tenant_id": "common"
}
}
]
}
MultipleAccountModeFragment.javaMultipleAccountModeFragment.java
Diese Datei veranschaulicht, wie Sie eine MSAL-App für mehrere Konten erstellen und eine Microsoft Graph-API aufrufen.This file demonstrates how to create a multiple account MSAL app and call a Microsoft Graph API.
Ein Beispiel für eine App mit mehreren Konten ist eine E-Mail-App, die Ihnen das Arbeiten mit mehreren Benutzerkonten ermöglich (z. B. ein Geschäftskonto und ein privates Konto).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 and a personal account.
MSAL-Initialisierung für mehrere KontenMultiple account MSAL initialization
In der Datei MultipleAccountModeFragment.java
wird in onCreateView()
ein App-Objekt für mehrere Konten (IMultipleAccountPublicClientApplication
) mit den in der Datei auth_config_multiple_account.json file
gespeicherten Konfigurationsinformationen erstellt: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) {
...
}
});
Das erstellte MultipleAccountPublicClientApplication
-Objekt wird in einer Klassenmember-Variablen gespeichert, sodass es für die Interaktion mit der MSAL-Bibliothek verwendet werden kann, um Token abzurufen und das Benutzerkonto zu laden und zu entfernen.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.
Laden eines KontosLoad an account
Apps für mehrere Konten rufen im Allgemeinen getAccounts()
auf, um das gewünschte Konto für MSAL-Vorgänge auszuwählen.Multiple account apps usually call getAccounts()
to select the account to use for MSAL operations. Der Code zum Laden eines Kontos befindet sich in der Datei MultipleAccountModeFragment.java
in loadAccounts()
.The code to load an account is in the MultipleAccountModeFragment.java
file, in loadAccounts()
. Das Laden des Benutzerkontos ist ein asynchroner Vorgang.Loading the user's account is an asynchronous operation. Daher werden die Situationen, in denen ein Konto geladen oder gewechselt oder ein Fehler auftritt, von einem Rückruf behandelt.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);
}
});
}
Interaktives Abrufen eines Tokens oder Abrufen eines Tokens im HintergrundGet a token interactively or silently
Es gibt einige Situationen, in denen der Benutzer aufgefordert werden kann, sein Konto auszuwählen, seine Anmeldeinformationen einzugeben oder den von der App angeforderten Berechtigungen zuzustimmen: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:
- Erstmaliges Anmelden von Benutzern bei der Anwendung.The first time users sign in to the application
- Wenn ein Benutzer sein Kennwort zurücksetzt, muss er seine Anmeldeinformationen eingeben.If a user resets their password, they'll need to enter their credentials
- Wenn die Zustimmung widerrufen wurdeIf consent is revoked
- Wenn die App explizit eine Zustimmung erfordertIf your app explicitly requires consent
- Wenn Ihre Anwendung zum ersten Mal Zugriff auf eine Ressource anfordertWhen your application is requesting access to a resource for the first time
- Wenn MFA oder andere Richtlinien für bedingten Zugriff erforderlich sindWhen MFA or other Conditional Access policies are required
Apps für mehrere Konten rufen Token im Allgemeinen interaktiv (d. h. der Benutzer muss über die Benutzeroberfläche Aktionen ausführen) mit einem Aufruf von acquireToken()
ab.Multiple account apps should typically acquire tokens interactively, that is with UI that involves the user, with a call to acquireToken()
. Der Code zum interaktiven Abrufen eines Tokens befindet sich in der Datei MultipleAccountModeFragment.java
in initializeUI()
im callGraphApiInteractiveButton
-Click-Handler: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 sollten nicht fordern, dass sich die Benutzer jedes Mal anmelden, wenn sie ein Token anfordern.Apps shouldn't require the user to sign in every time they request a token. Wenn sich der Benutzer bereits angemeldet hat, gestattet acquireTokenSilentAsync()
Apps das Anfordern von Token ohne Eingabeaufforderung für den Benutzer. Dies wird in der Datei MultipleAccountModeFragment.java
in initializeUI()
im callGraphApiSilentButton
-Click-Handler gezeigt: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());
Entfernen eines KontosRemove an account
Der Code zum Entfernen eines Kontos und aller zwischengespeicherten Token für das Konto befindet sich in der Datei MultipleAccountModeFragment.java
in initializeUI()
im Handler für die Schaltfläche zum Entfernen eines Kontos.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. Bevor Sie ein Konto entfernen können, benötigen Sie ein Kontoobjekt, das Sie von MSAL-Methoden wie getAccounts()
und acquireToken()
abrufen können.Before you can remove an account, you need an account object, which you obtain from MSAL methods like getAccounts()
and acquireToken()
. Da das Entfernen eines Kontos ein asynchroner Vorgang ist, wird der onRemoved
-Rückruf zum Aktualisieren der Benutzeroberfläche bereitgestellt.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
Dies ist die Konfigurationsdatei für eine MSAL-App, die mehrere Konten verwendet.This is the configuration file for a MSAL app that uses multiple accounts.
Eine Erläuterung der verschiedenen Felder finden Sie unter Android-MSAL-Konfigurationsdatei.See Understand the Android MSAL configuration file for an explanation of the various fields.
Im Unterschied zur Konfigurationsdatei auth_config_single_account.json enthält diese Konfigurationsdatei "account_mode" : "MULTIPLE"
anstelle von "account_mode" : "SINGLE"
, da es sich um eine App für mehrere Konten handelt.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"
ist für die Verwendung einer App-Objekt-Registrierung vorkonfiguriert, die von Microsoft verwaltet wird."client_id"
is preconfigured to use an app object registration that Microsoft maintains.
"redirect_uri"
ist so vorkonfiguriert, dass der Signaturschlüssel aus dem Codebeispiel verwendet wird."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": "AzureADandPersonalMicrosoftAccount",
"tenant_id": "common"
}
}
]
}
Hilfe und SupportHelp and support
Wenn Sie Hilfe benötigen, ein Problem melden möchten oder sich über Ihre Supportoptionen informieren möchten, finden Sie weitere Informationen unter Hilfe und Support für Entwickler.If you need help, want to report an issue, or want to learn about your support options, see Help and support for developers.
Nächste SchritteNext steps
Fahren Sie mit dem Android-Tutorial fort, in dem Sie eine Android-App erstellen, aus der ein Zugriffstoken von der Microsoft Identity Platform abgerufen wird, das dann in der App verwendet wird, um die Microsoft Graph-API aufzurufen.Move on to the Android tutorial in which you build an Android app that gets an access token from the Microsoft identity platform and uses it to call the Microsoft Graph API.