Tutorial: Prepare your iOS app for native authentication

This tutorial demonstrates how to add Microsoft Authentication Library (MSAL) native authentication SDK framework to your iOS Swift app.

In this tutorial, you learn how to:

  • Add the MSAL framework to an iOS app.
  • Create SDK instance.

Prerequisites

Add the MSAL framework to an iOS app

  1. Open your iOS project in Xcode.
  2. Select Add Package Dependencies... from the File menu.
  3. Enter https://github.com/AzureAD/microsoft-authentication-library-for-objc as the Package URL and choose Add Package

For more information and other mechanisms to add MSAL to your project, see the project Readme file.

Create SDK instance

  1. Import the MSAL library into your view controller by adding import MSAL at the top of your ViewController class.

  2. Add a nativeAuth member variable to your ViewController class by adding the following code just before the viewDidLoad() function:

    var nativeAuth: MSALNativeAuthPublicClientApplication!
    
  3. Next, add the following code to the viewDidLoad() function:

     do {
        nativeAuth = try MSALNativeAuthPublicClientApplication(
            clientId: "Enter_the_Application_Id_Here",
            tenantSubdomain: "Enter_the_Tenant_Subdomain_Here",
            challengeTypes: [.OOB]
        )
    
        print("Initialized Native Auth successfully.")
     } catch {
        print("Unable to initialize MSAL \(error)")
     }
    
  4. Replace the following values with the values from the Microsoft Entra admin center:

    1. Find the Enter_the_Application_Id_Here value and replace it with the Application (client) ID of the app you registered earlier.
    2. Find the Enter_the_Tenant_Subdomain_Here and replace it with the Directory (tenant) subdomain. For example, if your tenant primary domain is contoso.onmicrosoft.com, use contoso. If you don't have your Directory (tenant) subdomain, learn how to read your tenant details.
  5. To build, select the Product > Build in your project’s toolbar.

Optional: Logging configuration

MSAL provides a logging API that you can use to enable and configure logging. To see all debug output from MSAL add the following code at the start of the viewDidLoad() function:

MSALGlobalConfig.loggerConfig.logLevel = .verbose
MSALGlobalConfig.loggerConfig.setLogCallback { logLevel, message, containsPII in
   if !containsPII {
      print("MSAL: \(message ?? "")")
   }
}

This outputs all debug logs from MSAL, which can be helpful in diagnosing issues and learning how the native authentication flows work. To learn more about configuring log levels and best practices see Logging in MSAL for iOS/macOS.

Next steps