Редактиране

Споделяне чрез


Quickstart: Sign in users and call the Microsoft Graph API from an iOS or macOS app

Welcome! This probably isn't the page you were expecting. While we work on a fix, this link should take you to the right article:

Quickstart: Sign in users and call Microsoft Graph from an iOS or macOS app

We apologize for the inconvenience and appreciate your patience while we work to get this resolved.

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.

The quickstart applies to both iOS and macOS apps. Some steps are needed only for iOS apps and will be indicated as such.

Prerequisites

How the sample works

Shows how the sample app generated by this quickstart works

Step 1: Configure your application

For the code sample for this quickstart to work, add a Redirect URI compatible with the Auth broker.

Already configured Your application is configured with these attributes

Step 2: Download the sample project

Step 3: Install dependencies

  1. Extract the zip file.
  2. In a terminal window, navigate to the folder with the downloaded code sample and run pod install to install the latest MSAL library.

Step 4: 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.

Note

Enter_the_Supported_Account_Info_Here

  1. If you're building an app for Microsoft Entra national clouds, replace the line starting with 'let kGraphEndpoint' and 'let kAuthority' with correct endpoints. For global access, use default values:

    let kGraphEndpoint = "https://graph.microsoft.com/"
    let kAuthority = "https://login.microsoftonline.com/common"
    
  2. Other endpoints are documented here. For example, to run the quickstart with Microsoft Entra Germany, use following:

    let kGraphEndpoint = "https://graph.microsoft.de/"
    let kAuthority = "https://login.microsoftonline.de/common"
    
  3. Open the project settings. In the Identity section, enter the Bundle Identifier that you entered into the portal.

  4. Right-click Info.plist and select Open As > Source Code.

  5. Under the dict root node, replace Enter_the_bundle_Id_Here with the Bundle Id that you used in the portal. Notice the msauth. prefix in the string.

    <key>CFBundleURLTypes</key>
    <array>
       <dict>
          <key>CFBundleURLSchemes</key>
          <array>
             <string>msauth.Enter_the_Bundle_Id_Here</string>
          </array>
       </dict>
    </array>
    
  6. Build and run the app!

More Information

Read these sections to learn more about this quickstart.

Get MSAL

MSAL (MSAL.framework) is the library used to sign in users and request tokens used to access an API protected by Microsoft identity platform. You can add MSAL to your application using the following process:

$ vi Podfile

Add the following to this podfile (with your project's target):

use_frameworks!

target 'MSALiOS' do
   pod 'MSAL'
end

Run CocoaPods installation command:

pod install

Initialize MSAL

You can add the reference for MSAL by adding the following code:

import MSAL

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)
Where: Description
clientId The Application ID from the application registered in portal.azure.com
authority The Microsoft identity platform. In most of cases this will be https://login.microsoftonline.com/common >
redirectUri The redirect URI of the application. You can pass 'nil' to use the default value, or your custom redirect URI.

For iOS only, additional app requirements

Your app must also have the following in your AppDelegate. 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)
}

Note

On iOS 13+, if you adopt UISceneDelegate instead of UIApplicationDelegate, place this code into the scene:openURLContexts: callback instead (See Apple's documentation). 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)
}

Finally, your app must have an LSApplicationQueriesSchemes entry in your Info.plist alongside the CFBundleURLTypes. The sample comes with this included.

<key>LSApplicationQueriesSchemes</key>
<array>
   <string>msauthv2</string>
   <string>msauthv3</string>
</array>

Sign in users & request tokens

MSAL has two methods used to acquire tokens: acquireToken and acquireTokenSilent.

acquireToken: Get a token interactively

Some situations require users to interact with Microsoft identity platform. In these cases, the end user may be required to select their account, enter their credentials, or consent to your app's permissions. For example,

  • The first time users sign in to the application
  • If a user resets their password, they'll need to enter their credentials
  • When your application is requesting access to a resource for the first time
  • When 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 */}
Where: Description
scopes 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: Get an access token silently

Apps shouldn't require their users to sign in every time they request a token. 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 */}
}
Where: Description
scopes 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 The account a token is being requested for. This quickstart is about a single account application. If you want to build a multi-account app you'll need to define logic to identify which account to use for token requests using accountsFromDeviceForParameters:completionBlock: and passing correct accountIdentifier

Help and support

If you need help, want to report an issue, or want to learn about your support options, see Help and support for developers.

Next steps

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.