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

Applies to:
  • Microsoft identity platform endpoint
  • Microsoft Authentication Library (MSAL)

For a general availability (GA) library, use the Azure Active Directory (Azure AD) v1.0 endpoint and Azure AD Authentication Library (ADAL). For more info, see About v1.0.

This quickstart contains a code sample that demonstrates how a native iOS application can sign in personal, work and school accounts, get an access token, and call the Microsoft Graph API.

Shows how the sample app generated by this quickstart works

Note

Prerequisites

  • XCode 10+
  • iOS 10+

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 your 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, for example iOSQuickstart.
    • Skip other configurations on this page.
    • Hit the Register button.
  4. Click on the new app > go to Authentication > Add Platform > iOS.
    • Enter the Bundle Identifier for your application.
  5. Select Configure and save the MSAL Configuration details for later.

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 your web server or project

Step 3: 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:

    let kClientID = "Enter_the_Application_Id_here"
    let kAuthority = "https://login.microsoftonline.com/Enter_the_Tenant_Info_Here"
    
  3. Right click Info.plist and select Open As > Source Code.

  4. Under the dict root node, replace with your Bundle Id:

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

Note

This quickstart supports Enter_the_Supported_Account_Info_Here.

  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:

    let kClientID = "<ENTER_YOUR_APPLICATION/CLIENT_ID>"
    
    
  3. Right click Info.plist and select Open As > Source Code.

  4. Under the dict root node, replace with your Bundle Id:

    <key>CFBundleURLTypes</key>
    <array>
       <dict>
          <key>CFBundleURLSchemes</key>
          <array>
             <string>msauth.<ENTER_YOUR_BUNDLE_ID></string>
          </array>
       </dict>
    </array>
    
    
  5. Build & run the app!

More Information

Read these sections to learn more about this quickstart.

Getting 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', '~> 0.4.0'
end

MSAL initialization

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

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 perform authentication.

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        guard let sourceApplication = options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String else {
            return false
        }
        
        return MSALPublicClientApplication.handleMSALResponse(url, sourceApplication: sourceApplication)
    }

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

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

Sign in users & Request tokens

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

acquireToken: Getting 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 will 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)
applicationContext.acquireToken(with: parameters) { (result, error) in /* Add your handling logic */}
Where:
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: Getting 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.

let parameters = MSALSilentTokenParameters(scopes: kScopes, account: applicationContext.allAccounts().first)
applicationContext.acquireTokenSilent(with: parameters) { (result, error) in /* Add your handling logic */}
Where:
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 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 applicationContext.account(forHomeAccountId: self.homeAccountId)

Next steps

Try out the iOS tutorial for a complete step-by-step guide on building applications, including a complete explanation of this quickstart.

Learn the steps to create the application used in this quickstart

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:

Help us improve the Microsoft identity platform. Tell us what you think by completing a short two-question survey.