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

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

Register and download your quickstart app

You have two options to start your quickstart application:

Option 1: Register and auto configure your app and then download the code sample

Step 1: Register your application

To register your app,

  1. Go to the new Azure portal - App registrations pane.
  2. Enter a name for your application and select Register.
  3. Follow the instructions to download and automatically configure your new application with just one click.

Option 2: Register and manually configure your application and code sample

Step 1: Register your application

To register your application and add the app's registration information to your solution manually, follow these steps:

  1. Navigate to the Microsoft identity platform for developers App registrations page.
  2. Select New registration.
  3. When the Register an application page appears, enter your application's registration information:
    • In the Name section, enter a meaningful application name that will be displayed to users of the app when they sign in or consent to your app.
    • Skip other configurations on this page.
    • Select Register.
  4. In the Manage section, select Authentication > Add Platform > iOS.
    • Enter the Bundle Identifier for your application. The bundle identifier is just a unique string that uniquely identifies your application, for example com.<yourname>.identitysample.MSALMacOS. Make a note of the value you use.
    • Note that the iOS configuration is also applicable to macOS applications.
  5. Select Configure and save the MSAL Configuration details for later in this quickstart.

Step 1: Configure your application

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

Step 2: Download the sample project

Step 3: Install dependencies

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

Step 4: Configure your project

If you selected Option 1 above, you can skip these steps.

  1. Extract the zip file and open the project in XCode.

  2. Edit ViewController.swift and replace the line starting with 'let kClientID' with the following code snippet. Remember to update the value for kClientID 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"
    
  3. If you're building an app for Azure AD 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"
    
  4. Other endpoints are documented here. 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"
    
  5. Open the project settings. In the Identity section, enter the Bundle Identifier that you entered into the portal.

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

  7. Under the dict root node, replace Enter_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>
    
    
  8. Build & 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 endpoint. 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 would like 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.