Schnellstart: Anmelden von Benutzern und Aufrufen der Microsoft Graph-API aus einer iOS- oder macOS-AppQuickstart: Sign in users and call the Microsoft Graph API from an iOS or macOS app
In dieser Schnellstartanleitung laden Sie ein Codebeispiel herunter und führen es aus, das zeigt, wie eine native iOS- oder macOS-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 a native iOS or macOS application can sign in users and get an access token to call the Microsoft Graph API.
Die Schnellstartanleitung gilt für iOS- und macOS-Apps.The quickstart applies to both iOS and macOS apps. Einige Schritte sind nur für iOS-Apps erforderlich und entsprechend gekennzeichnet.Some steps are needed only for iOS apps and will be indicated as such.
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.
- XCode 10 oder höherXCode 10+
- iOS 10 oder höheriOS 10+
- macOS 10.12 oder höhermacOS 10.12+
Funktionsweise des BeispielsHow the sample works
Registrieren und Herunterladen Ihrer Schnellstart-AppRegister and download your quickstart app
Die Schnellstartanwendung kann auf zwei Arten gestartet werden:You have two options to start your quickstart application:
- [Express] Option 1: Registrieren und automatisches Konfigurieren Ihrer App und anschließendes Herunterladen des Codebeispiels[Express] Option 1: Register and auto configure your app and then download your code sample
- [Manuell] Option 2: Registrieren und manuelles Konfigurieren Ihrer Anwendung und des Codebeispiels[Manual] Option 2: Register and manually configure your application and code sample
Option 1: Registrieren und automatisches Konfigurieren Ihrer App und anschließendes Herunterladen des CodebeispielsOption 1: Register and auto configure your app and then download the code sample
Schritt 1: Anwendung registrierenStep 1: Register your application
So registrieren Sie Ihre App:To register your app,
- Navigieren Sie zur Umgebung des Schnellstarts Azure-Portal – App-Registrierungen.Go to the Azure portal - App registrations quickstart experience.
- Geben Sie einen Namen für Ihre Anwendung ein, und wählen Sie Registrieren aus.Enter a name for your application and select Register.
- Befolgen Sie die Anweisungen, um Ihre neue Anwendung mit nur einem Klick herunterzuladen und automatisch zu konfigurieren.Follow the instructions to download and automatically configure your new application with just one click.
Option 2: Registrieren und manuelles Konfigurieren Ihrer Anwendung und des CodebeispielsOption 2: Register and manually configure your application and code sample
Schritt 1: Anwendung registrierenStep 1: Register your application
Führen Sie die folgenden Schritte aus, um Ihre Anwendung zu registrieren und Ihrer Projektmappe manuell die Registrierungsinformationen Ihrer App hinzuzufügen:To register your application and add the app's registration information to your solution manually, follow these steps:
- Melden Sie sich beim Azure-Portal an.Sign in to the Azure portal.
- Wenn Sie Zugriff auf mehrere Mandanten haben, verwenden Sie im Menü am oberen Rand den Filter Verzeichnis + Abonnement
, um den Mandanten auszuwählen, für den Sie eine Anwendung registrieren möchten.
- Suchen Sie nach Azure Active Directory, und wählen Sie diese Option aus.Search for and select Azure Active Directory.
- Wählen Sie unter Verwalten Folgendes aus: App-Registrierungen > Neue Registrierung.Under Manage, select App registrations > New registration.
- Geben Sie einen Namen für Ihre Anwendung ein.Enter a Name for your application. Benutzern Ihrer App wird wahrscheinlich dieser Namen angezeigt. Sie können ihn später ändern.Users of your app might see this name, and you can change it later.
- Wählen Sie Registrieren.Select Register.
- Wählen Sie unter Verwalten die Optionen Authentifizierung > Plattform hinzufügen > iOS aus.Under Manage, select Authentication > Add Platform > iOS.
- Geben Sie die Paket-ID für Ihre Anwendung ein.Enter the Bundle Identifier for your application. Die Paket-ID ist eine eindeutige Zeichenfolge, die Ihre Anwendung eindeutig identifiziert (z. B.
com.<yourname>.identitysample.MSALMacOS
).The bundle identifier is a unique string that uniquely identifies your application, for examplecom.<yourname>.identitysample.MSALMacOS
. Notieren Sie sich den verwendeten Wert.Make a note of the value you use. Die iOS-Konfiguration ist auch bei macOS-Anwendungen anwendbar.Note that the iOS configuration is also applicable to macOS applications. - Wählen Sie Konfigurieren aus, und speichern Sie die Details der MSAL-Konfiguration zur späteren Verwendung in diesem Schnellstart.Select Configure and save the MSAL Configuration details for later in this quickstart.
- Wählen Sie Fertig aus.Select Done.
Schritt 1: Konfigurieren der AnwendungStep 1: Configure your application
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.
: Ihre Anwendung ist mit diesen Attributen konfiguriert.
Your application is configured with these attributes
Schritt 2: Herunterladen des BeispielprojektsStep 2: Download the sample project
Schritt 2: Herunterladen des BeispielprojektsStep 2: Download the sample project
Schritt 3: Installieren von AbhängigkeitenStep 3: Install dependencies
Navigieren Sie in einem Terminalfenster zu dem Ordner, der das heruntergeladene Codebeispiel enthält, und führen Sie pod install
zum Installieren der MSAL-Bibliothek aus.In a terminal window, navigate to the folder with the downloaded code sample and run pod install
to install the latest MSAL library.
Schritt 4: Ihre App ist konfiguriert und betriebsbereitStep 4: 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.
Hinweis
Enter_the_Supported_Account_Info_Here
Schritt 4: Konfigurieren des ProjektsStep 4: Configure your project
Wenn Sie weiter oben die erste Option ausgewählt haben, können Sie diese Schritte überspringen.If you selected Option 1 above, you can skip these steps.
Extrahieren Sie die ZIP-Datei, und öffnen Sie das Projekt in XCode.Extract the zip file and open the project in XCode.
Bearbeiten Sie ViewController.swift, und ersetzen Sie die Zeile, die mit „let kClientID“ beginnt, durch den folgenden Codeausschnitt.Edit ViewController.swift and replace the line starting with 'let kClientID' with the following code snippet. Sie müssen den Wert für
kClientID
durch die Client-ID ersetzen, die Sie zuvor im Schnellstart beim Registrieren Ihrer App im Portal gespeichert haben:Remember to update the value forkClientID
with the clientID that you saved when you registered your app in the portal earlier in this quickstart:let kClientID = "Enter_the_Application_Id_Here"
Ersetzen Sie beim Erstellen einer App für nationale Azure AD-Clouds die Zeile, die mit „let kGraphEndpoint“ und „let kAuthority“ beginnt, durch richtige Endpunkte.If you're building an app for Azure AD national clouds, replace the line starting with 'let kGraphEndpoint' and 'let kAuthority' with correct endpoints. Verwenden Sie für globalen Zugriff die Standardwerte:For global access, use default values:
let kGraphEndpoint = "https://graph.microsoft.com/" let kAuthority = "https://login.microsoftonline.com/common"
Informationen zu anderen Endpunkten finden Sie hier.Other endpoints are documented here. Verwenden Sie beispielsweise zum Ausführen der Schnellstartanleitung mit Azure AD Deutschland Folgendes:For example, to run the quickstart with Azure AD Germany, use following:
let kGraphEndpoint = "https://graph.microsoft.de/" let kAuthority = "https://login.microsoftonline.de/common"
Öffnen Sie die Projekteinstellungen.Open the project settings. Geben Sie im Abschnitt Identität den Wert für Bundle Identifier (Paket-ID) ein, den Sie im Portal angegeben haben.In the Identity section, enter the Bundle Identifier that you entered into the portal.
Klicken Sie mit der rechten Maustaste auf Info.plist, und wählen Sie Öffnen als > Quellcode aus.Right-click Info.plist and select Open As > Source Code.
Ersetzen Sie unter dem Stammknoten „dict“
Enter_the_bundle_Id_Here
durch den Wert für *Bündel-ID _, den Sie im Portal verwendet haben.Under the dict root node, replaceEnter_the_bundle_Id_Here
with the *Bundle Id _ that you used in the portal.<key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleURLSchemes</key> <array> <string>msauth.Enter_the_Bundle_Id_Here</string> </array> </dict> </array>
Erstellen Sie die App, und führen Sie die App aus!Build & run the app!
Weitere InformationenMore Information
Lesen Sie diese Abschnitte, um mehr über diesen Schnellstart zu erfahren.Read these sections to learn more about this quickstart.
Abrufen von MSALGet MSAL
MSAL (MSAL.framework) ist die Bibliothek zum Anmelden von Benutzern und zum Anfordern von Token, die für den Zugriff auf eine durch Microsoft Identity Platform geschützte API verwendet werden.MSAL (MSAL.framework) is the library used to sign in users and request tokens used to access an API protected by Microsoft identity platform. Sie können Ihrer Anwendung MSAL mithilfe des folgenden Vorgangs hinzufügen:You can add MSAL to your application using the following process:
$ vi Podfile
Fügen Sie der Podfile-Datei den folgenden Code (mit dem Ziel Ihres Projekts) hinzu:Add the following to this podfile (with your project's target):
use_frameworks!
target 'MSALiOS' do
pod 'MSAL'
end
Ausführen des CocoaPods-Installationsbefehls:Run CocoaPods installation command:
pod install
MSAL initialisierenInitialize MSAL
Sie können den Verweis auf MSAL hinzufügen, indem Sie den folgenden Code hinzufügen:You can add the reference for MSAL by adding the following code:
import MSAL
Initialisieren Sie MSAL anschließend mit dem folgenden Code:Then, initialize MSAL using the following code:
let authority = try MSALAADAuthority(url: URL(string: kAuthority)!)
let msalConfiguration = MSALPublicClientApplicationConfig(clientId: kClientID, redirectUri: nil, authority: authority)
self.applicationContext = try MSALPublicClientApplication(configuration: msalConfiguration)
Hierbei gilt:Where: BESCHREIBUNGDescription clientId
Die Anwendungs-ID der in _portal.azure.com* registrierten AnwendungThe Application ID from the application registered in _portal.azure.com* authority
Der Microsoft Identity Platform-Endpunkt.The Microsoft identity platform endpoint. In den meisten Fällen ist dies https://login.microsoftonline.com/common
.In most of cases this will behttps://login.microsoftonline.com/common
redirectUri
Der Umleitungs-URI der Anwendung.The redirect URI of the application. Sie können „nil“ übergeben, um den Standardwert zu verwenden, oder Ihren benutzerdefinierten Umleitungs-URI angeben.You can pass 'nil' to use the default value, or your custom redirect URI.
Nur iOS: zusätzliche App-AnforderungenFor iOS only, additional app requirements
Ihre App muss auch Folgendes in AppDelegate
enthalten.Your app must also have the following in your AppDelegate
. Dadurch kann das MSAL SDK die Tokenantwort der Authentifizierungsbroker-App verarbeiten, wenn Sie die Authentifizierung ausführen.This lets MSAL SDK handle token response from the Auth broker app when you do authentication.
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
return MSALPublicClientApplication.handleMSALResponse(url, sourceApplication: options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String)
}
Hinweis
Wenn Sie unter iOS 13 oder höher UISceneDelegate
anstelle von UIApplicationDelegate
übernehmen, platzieren Sie diesen Code stattdessen im scene:openURLContexts:
-Rückruf (siehe Dokumentation von Apple).On iOS 13+, if you adopt UISceneDelegate
instead of UIApplicationDelegate
, place this code into the scene:openURLContexts:
callback instead (See Apple's documentation).
Wenn Sie sowohl UISceneDelegate als auch UIApplicationDelegate für die Kompatibilität mit älteren iOS-Versionen unterstützen, muss der MSAL-Rückruf für beide Optionen zur Verfügung gestellt werden.If you support both UISceneDelegate and UIApplicationDelegate for compatibility with older iOS, MSAL callback needs to be placed into both places.
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
guard let urlContext = URLContexts.first else {
return
}
let url = urlContext.url
let sourceApp = urlContext.options.sourceApplication
MSALPublicClientApplication.handleMSALResponse(url, sourceApplication: sourceApp)
}
Ihre App muss neben CFBundleURLTypes
über einen LSApplicationQueriesSchemes
-Eintrag in *Info.plist _ verfügen.Finally, your app must have an LSApplicationQueriesSchemes
entry in your *Info.plist _ alongside the CFBundleURLTypes
. Im Beispiel ist dies enthalten.The sample comes with this included.
<key>LSApplicationQueriesSchemes</key>
<array>
<string>msauthv2</string>
<string>msauthv3</string>
</array>
Anmelden von Benutzern und Anfordern von TokenSign in users & request tokens
MSAL verfügt über zwei Methoden, die zum Abrufen von Token verwendet werden: acquireToken
und acquireTokenSilent
.MSAL has two methods used to acquire tokens: acquireToken
and acquireTokenSilent
.
acquireToken: Interaktives Abrufen eines TokensacquireToken: Get a token interactively
In einigen Situationen müssen Benutzer mit Microsoft Identity Platform interagieren.Some situations require users to interact with Microsoft identity platform. In diesen Fällen muss der Endbenutzer möglicherweise sein Konto auswählen, seine Anmeldeinformationen eingeben oder den Berechtigungen Ihrer App zustimmen.In these cases, the end user may be required to select their account, enter their credentials, or consent to your app's permissions. Beispiel:For example,
_ 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 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
let parameters = MSALInteractiveTokenParameters(scopes: kScopes, webviewParameters: self.webViewParamaters!)
self.applicationContext!.acquireToken(with: parameters) { (result, error) in /* Add your handling logic */}
Hierbei gilt:Where: BESCHREIBUNGDescription scopes
Enthält die angeforderten Bereiche ( [ "user.read" ]
für Microsoft Graph oder[ "<Application ID URL>/scope" ]
für benutzerdefinierte Web-APIs (api://<Application ID>/access_as_user
))Contains the scopes being requested (that is,[ "user.read" ]
for Microsoft Graph or[ "<Application ID URL>/scope" ]
for custom web APIs (api://<Application ID>/access_as_user
)
acquireTokenSilent: Abrufen eines Zugriffstokens im HintergrundacquireTokenSilent: Get an access token silently
Apps sollten nicht verlangen, dass sich die Benutzer jedes Mal anmelden, wenn sie ein Token anfordern.Apps shouldn't require their users to sign in every time they request a token. Wenn sich der Benutzer bereits angemeldet hat, haben Apps durch diese Methode die Möglichkeit, Token im Hintergrund anzufordern.If the user has already signed in, this method allows apps to request tokens silently.
self.applicationContext!.getCurrentAccount(with: nil) { (currentAccount, previousAccount, error) in
guard let account = currentAccount else {
return
}
let silentParams = MSALSilentTokenParameters(scopes: self.kScopes, account: account)
self.applicationContext!.acquireTokenSilent(with: silentParams) { (result, error) in /* Add your handling logic */}
}
Hierbei gilt:Where: BESCHREIBUNGDescription scopes
Enthält die angeforderten Bereiche ( [ "user.read" ]
für Microsoft Graph oder[ "<Application ID URL>/scope" ]
für benutzerdefinierte Web-APIs (api://<Application ID>/access_as_user
))Contains the scopes being requested (that is,[ "user.read" ]
for Microsoft Graph or[ "<Application ID URL>/scope" ]
for custom web APIs (api://<Application ID>/access_as_user
)account
Das Konto, für das ein Token angefordert wird.The account a token is being requested for. In dieser Schnellstartanleitung wird eine einzelne Kontoanwendung angezeigt.This quickstart is about a single account application. Wenn Sie eine App mit mehreren Konten erstellen möchten, müssen Sie die Logik zum Identifizieren des gewünschten Kontos für Tokenanforderungen mit accountsFromDeviceForParameters:completionBlock:
definieren und den richtigenaccountIdentifier
übergeben.If you want to build a multi-account app you'll need to define logic to identify which account to use for token requests usingaccountsFromDeviceForParameters:completionBlock:
and passing correctaccountIdentifier
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 Schritt-für-Schritt-Tutorial fort, in dem Sie eine iOS- oder macOS-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 step-by-step tutorial in which you build an iOS or macOS app that gets an access token from the Microsoft identity platform and uses it to call the Microsoft Graph API.