|
| 1 | +--- |
| 2 | +title: "Quickstart: Add sign in with Microsoft to an iOS or macOS app | Azure" |
| 3 | +titleSuffix: Microsoft identity platform |
| 4 | +description: In this quickstart, learn how an iOS or macOS app can sign in users, get an access token from the Microsoft identity platform, and call the Microsoft Graph API. |
| 5 | +services: active-directory |
| 6 | +author: mmacy |
| 7 | +manager: CelesteDG |
| 8 | +ms.service: active-directory |
| 9 | +ms.subservice: develop |
| 10 | +ms.topic: portal |
| 11 | +ms.workload: identity |
| 12 | +ms.date: 02/15/2022 |
| 13 | +ROBOTS: NOINDEX |
| 14 | +ms.author: marsma |
| 15 | +ms.reviewer: jmprieur, saeeda |
| 16 | +ms.custom: aaddev, identityplatformtop40, "scenarios:getting-started", "languages:iOS", mode-api |
| 17 | +#Customer intent: As an application developer, I want to learn how to sign in users and call Microsoft Graph from my iOS or macOS application. |
| 18 | +--- |
| 19 | + |
| 20 | +# Quickstart: Sign in users and call the Microsoft Graph API from an iOS or macOS app |
| 21 | + |
| 22 | +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. |
| 23 | + |
| 24 | +The quickstart applies to both iOS and macOS apps. Some steps are needed only for iOS apps and will be indicated as such. |
| 25 | + |
| 26 | +## Prerequisites |
| 27 | + |
| 28 | +* An Azure account with an active subscription. [Create an account for free](https://azure.microsoft.com/free/?WT.mc_id=A261C142F). |
| 29 | +* XCode 10+ |
| 30 | +* iOS 10+ |
| 31 | +* macOS 10.12+ |
| 32 | + |
| 33 | +## How the sample works |
| 34 | + |
| 35 | + |
| 36 | + |
| 37 | +#### Step 1: Configure your application |
| 38 | +For the code sample for this quickstart to work, add a **Redirect URI** compatible with the Auth broker. |
| 39 | +> [!div id="makechanges" class="nextstepaction" class="configure-app-button"] |
| 40 | +> [Make this change for me]() |
| 41 | +
|
| 42 | +> [!div id="appconfigured" class="alert alert-info"] |
| 43 | +>  Your application is configured with these attributes |
| 44 | +
|
| 45 | +#### Step 2: Download the sample project |
| 46 | +> [!div class="nextstepaction"] |
| 47 | +> [Download the code sample for iOS]() |
| 48 | +
|
| 49 | +> [!div class="nextstepaction"] |
| 50 | +> [Download the code sample for macOS]() |
| 51 | +
|
| 52 | +#### Step 3: Install dependencies |
| 53 | + |
| 54 | +1. Extract the zip file. |
| 55 | +2. In a terminal window, navigate to the folder with the downloaded code sample and run `pod install` to install the latest MSAL library. |
| 56 | + |
| 57 | +#### Step 4: Your app is configured and ready to run |
| 58 | +We have configured your project with values of your app's properties and it's ready to run. |
| 59 | +> [!NOTE] |
| 60 | +> `Enter_the_Supported_Account_Info_Here` |
| 61 | +
|
| 62 | +1. If you're building an app for [Azure AD national clouds](/graph/deployments#app-registration-and-token-service-root-endpoints), replace the line starting with 'let kGraphEndpoint' and 'let kAuthority' with correct endpoints. For global access, use default values: |
| 63 | + |
| 64 | + ```swift |
| 65 | + let kGraphEndpoint = "https://graph.microsoft.com/" |
| 66 | + let kAuthority = "https://login.microsoftonline.com/common" |
| 67 | + ``` |
| 68 | + |
| 69 | +1. Other endpoints are documented [here](/graph/deployments#app-registration-and-token-service-root-endpoints). For example, to run the quickstart with Azure AD Germany, use following: |
| 70 | + |
| 71 | + ```swift |
| 72 | + let kGraphEndpoint = "https://graph.microsoft.de/" |
| 73 | + let kAuthority = "https://login.microsoftonline.de/common" |
| 74 | + ``` |
| 75 | + |
| 76 | +3. Open the project settings. In the **Identity** section, enter the **Bundle Identifier** that you entered into the portal. |
| 77 | +4. Right-click **Info.plist** and select **Open As** > **Source Code**. |
| 78 | +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. |
| 79 | + |
| 80 | + ```xml |
| 81 | + <key>CFBundleURLTypes</key> |
| 82 | + <array> |
| 83 | + <dict> |
| 84 | + <key>CFBundleURLSchemes</key> |
| 85 | + <array> |
| 86 | + <string>msauth.Enter_the_Bundle_Id_Here</string> |
| 87 | + </array> |
| 88 | + </dict> |
| 89 | + </array> |
| 90 | + ``` |
| 91 | + |
| 92 | +6. Build and run the app! |
| 93 | + |
| 94 | +## More Information |
| 95 | + |
| 96 | +Read these sections to learn more about this quickstart. |
| 97 | + |
| 98 | +### Get MSAL |
| 99 | + |
| 100 | +MSAL ([MSAL.framework](https://github.com/AzureAD/microsoft-authentication-library-for-objc)) 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: |
| 101 | + |
| 102 | +``` |
| 103 | +$ vi Podfile |
| 104 | +``` |
| 105 | + |
| 106 | +Add the following to this podfile (with your project's target): |
| 107 | + |
| 108 | +``` |
| 109 | +use_frameworks! |
| 110 | +
|
| 111 | +target 'MSALiOS' do |
| 112 | + pod 'MSAL' |
| 113 | +end |
| 114 | +``` |
| 115 | + |
| 116 | +Run CocoaPods installation command: |
| 117 | + |
| 118 | +`pod install` |
| 119 | + |
| 120 | +### Initialize MSAL |
| 121 | + |
| 122 | +You can add the reference for MSAL by adding the following code: |
| 123 | + |
| 124 | +```swift |
| 125 | +import MSAL |
| 126 | +``` |
| 127 | + |
| 128 | +Then, initialize MSAL using the following code: |
| 129 | + |
| 130 | +```swift |
| 131 | +let authority = try MSALAADAuthority(url: URL(string: kAuthority)!) |
| 132 | + |
| 133 | +let msalConfiguration = MSALPublicClientApplicationConfig(clientId: kClientID, redirectUri: nil, authority: authority) |
| 134 | +self.applicationContext = try MSALPublicClientApplication(configuration: msalConfiguration) |
| 135 | +``` |
| 136 | + |
| 137 | +> |Where: | Description | |
| 138 | +> |---------|---------| |
| 139 | +> | `clientId` | The Application ID from the application registered in *portal.azure.com* | |
| 140 | +> | `authority` | The Microsoft identity platform. In most of cases this will be `https://login.microsoftonline.com/common` | |
| 141 | +> | `redirectUri` | The redirect URI of the application. You can pass 'nil' to use the default value, or your custom redirect URI. | |
| 142 | +
|
| 143 | +### For iOS only, additional app requirements |
| 144 | + |
| 145 | +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. |
| 146 | + |
| 147 | +```swift |
| 148 | +func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool { |
| 149 | + |
| 150 | + return MSALPublicClientApplication.handleMSALResponse(url, sourceApplication: options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String) |
| 151 | +} |
| 152 | +``` |
| 153 | + |
| 154 | +> [!NOTE] |
| 155 | +> On iOS 13+, if you adopt `UISceneDelegate` instead of `UIApplicationDelegate`, place this code into the `scene:openURLContexts:` callback instead (See [Apple's documentation](https://developer.apple.com/documentation/uikit/uiscenedelegate/3238059-scene?language=objc)). |
| 156 | +> If you support both UISceneDelegate and UIApplicationDelegate for compatibility with older iOS, MSAL callback needs to be placed into both places. |
| 157 | +
|
| 158 | +```swift |
| 159 | +func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) { |
| 160 | + |
| 161 | + guard let urlContext = URLContexts.first else { |
| 162 | + return |
| 163 | + } |
| 164 | + |
| 165 | + let url = urlContext.url |
| 166 | + let sourceApp = urlContext.options.sourceApplication |
| 167 | + |
| 168 | + MSALPublicClientApplication.handleMSALResponse(url, sourceApplication: sourceApp) |
| 169 | +} |
| 170 | +``` |
| 171 | + |
| 172 | +Finally, your app must have an `LSApplicationQueriesSchemes` entry in your ***Info.plist*** alongside the `CFBundleURLTypes`. The sample comes with this included. |
| 173 | + |
| 174 | + ```xml |
| 175 | + <key>LSApplicationQueriesSchemes</key> |
| 176 | + <array> |
| 177 | + <string>msauthv2</string> |
| 178 | + <string>msauthv3</string> |
| 179 | + </array> |
| 180 | + ``` |
| 181 | + |
| 182 | +### Sign in users & request tokens |
| 183 | + |
| 184 | +MSAL has two methods used to acquire tokens: `acquireToken` and `acquireTokenSilent`. |
| 185 | + |
| 186 | +#### acquireToken: Get a token interactively |
| 187 | + |
| 188 | +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, |
| 189 | + |
| 190 | +* The first time users sign in to the application |
| 191 | +* If a user resets their password, they'll need to enter their credentials |
| 192 | +* When your application is requesting access to a resource for the first time |
| 193 | +* When MFA or other Conditional Access policies are required |
| 194 | + |
| 195 | +```swift |
| 196 | +let parameters = MSALInteractiveTokenParameters(scopes: kScopes, webviewParameters: self.webViewParamaters!) |
| 197 | +self.applicationContext!.acquireToken(with: parameters) { (result, error) in /* Add your handling logic */} |
| 198 | +``` |
| 199 | + |
| 200 | +> |Where:| Description | |
| 201 | +> |---------|---------| |
| 202 | +> | `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`) | |
| 203 | +
|
| 204 | +#### acquireTokenSilent: Get an access token silently |
| 205 | + |
| 206 | +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. |
| 207 | + |
| 208 | +```swift |
| 209 | +self.applicationContext!.getCurrentAccount(with: nil) { (currentAccount, previousAccount, error) in |
| 210 | + |
| 211 | + guard let account = currentAccount else { |
| 212 | + return |
| 213 | + } |
| 214 | + |
| 215 | + let silentParams = MSALSilentTokenParameters(scopes: self.kScopes, account: account) |
| 216 | + self.applicationContext!.acquireTokenSilent(with: silentParams) { (result, error) in /* Add your handling logic */} |
| 217 | +} |
| 218 | +``` |
| 219 | + |
| 220 | +> |Where: | Description | |
| 221 | +> |---------|---------| |
| 222 | +> | `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`) | |
| 223 | +> | `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` | |
| 224 | +
|
| 225 | +[!INCLUDE [Help and support](../../../includes/active-directory-develop-help-support-include.md)] |
| 226 | + |
| 227 | +## Next steps |
| 228 | + |
| 229 | +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. |
| 230 | + |
| 231 | +> [!div class="nextstepaction"] |
| 232 | +> [Tutorial: Sign in users and call Microsoft Graph from an iOS or macOS app](tutorial-v2-ios.md) |
0 commit comments