Microsoft Authentication for Mobile: Getting Started

Okay, here’s a comprehensive article on “Microsoft Authentication for Mobile: Getting Started,” aiming for approximately 5000 words and covering various aspects in detail.

Microsoft Authentication for Mobile: Getting Started

Mobile applications have become ubiquitous, serving everything from social networking and banking to healthcare and enterprise workflows. Securing these applications is paramount, and a robust authentication system forms the bedrock of that security. Microsoft, with its vast ecosystem of services and a strong focus on security, provides a comprehensive suite of tools and libraries to implement authentication in mobile applications. This article serves as a detailed guide to getting started with Microsoft Authentication for mobile, covering various platforms, libraries, and best practices.

1. Why Microsoft Authentication?

Before diving into the technical details, it’s crucial to understand why you might choose Microsoft’s authentication services for your mobile app. Here are several compelling reasons:

  • Unified Identity Platform: Microsoft’s identity platform (formerly known as Azure Active Directory, now part of Microsoft Entra) provides a single, consistent identity for users across various Microsoft services (Office 365, Azure, Dynamics 365) and even third-party applications. This means users can leverage their existing Microsoft accounts, reducing friction and improving the user experience.
  • Security and Compliance: Microsoft invests heavily in security and compliance. Their authentication services adhere to industry standards like OAuth 2.0 and OpenID Connect, and they offer features like multi-factor authentication (MFA), conditional access, and identity protection to mitigate various security threats.
  • Scalability and Reliability: Microsoft’s cloud-based infrastructure is designed for massive scale and high availability. Your authentication system can handle a growing user base without performance degradation.
  • Developer-Friendly Tools and Libraries: Microsoft provides well-documented SDKs and libraries for various mobile platforms (iOS, Android, Xamarin, React Native, Flutter), simplifying the integration process. These libraries handle much of the complex OAuth 2.0 and OpenID Connect flow, allowing developers to focus on their application’s core functionality.
  • Integration with Microsoft Services: If your mobile app needs to interact with other Microsoft services (e.g., accessing data from Microsoft Graph, using Azure services), using Microsoft Authentication provides seamless integration and simplifies authorization.
  • Support for Different User Types: Microsoft’s identity platform supports various user types, including:
    • Work or School Accounts (Microsoft Entra ID): For organizational users within a company or educational institution.
    • Personal Microsoft Accounts (MSA): For individual users (e.g., Outlook.com, Xbox Live).
    • Social Accounts (Azure AD B2C): Allows users to sign in with their existing social accounts (Facebook, Google, Twitter, etc.).
    • External Identities (Azure AD B2B): Enables collaboration with users from other organizations.
  • Cost-Effectiveness: Microsoft offers various pricing tiers, including a free tier for basic usage, making it accessible for developers and small businesses.

2. Key Concepts and Terminology

Understanding the core concepts and terminology is crucial for effectively implementing Microsoft Authentication. Here’s a breakdown of the key terms:

  • Microsoft Entra ID (formerly Azure Active Directory): Microsoft’s cloud-based identity and access management service. It’s the directory that stores user accounts, groups, and application registrations.
  • Microsoft Identity Platform: The overarching platform encompassing Microsoft Entra ID and related services, providing a unified identity solution.
  • OAuth 2.0: An industry-standard authorization framework that allows third-party applications to access resources on behalf of a user without requiring the user to share their credentials directly with the application.
  • OpenID Connect (OIDC): An authentication layer built on top of OAuth 2.0. It provides a standardized way to verify the identity of a user and obtain basic profile information.
  • Access Token: A credential that represents the authorization granted to an application to access specific resources on behalf of a user. Access tokens typically have a limited lifespan.
  • Refresh Token: A long-lived credential that can be used to obtain new access tokens without requiring the user to re-authenticate. This improves the user experience by reducing the frequency of login prompts.
  • ID Token: A JSON Web Token (JWT) that contains information about the authenticated user (e.g., user ID, name, email). It’s used to verify the user’s identity.
  • Application Registration: The process of registering your mobile application with Microsoft Entra ID. This creates an application object that represents your app within the identity platform and allows you to configure authentication settings.
  • Client ID (Application ID): A unique identifier assigned to your application during registration. It’s used to identify your app to the Microsoft identity platform.
  • Redirect URI (Reply URL): The URI to which the Microsoft identity platform will redirect the user after authentication. This is typically a custom URI scheme handled by your mobile application.
  • Scopes (Permissions): Define the specific resources or actions that your application is requesting access to. For example, User.Read allows your app to read the user’s basic profile information.
  • Microsoft Authentication Library (MSAL): A set of client libraries provided by Microsoft that simplify the implementation of OAuth 2.0 and OpenID Connect flows in your mobile applications. MSAL handles token acquisition, caching, and renewal.
  • Microsoft Graph: A unified API endpoint that provides access to data and services across Microsoft 365, Windows 10, and Enterprise Mobility + Security.
  • Single Sign-On (SSO): Allows users to sign in once and access multiple applications without being prompted to re-authenticate.
  • Multi-Factor Authentication (MFA): Adds an extra layer of security by requiring users to provide multiple forms of verification (e.g., password + one-time code from an authenticator app).
  • Conditional Access: Allows administrators to define policies that control access to resources based on various conditions (e.g., user location, device compliance, sign-in risk).
  • Azure AD B2C (Business-to-Consumer): A specific offering within Microsoft Entra that’s tailored for consumer-facing applications. It allows users to sign in with their existing social media accounts (Facebook, Google, etc.) or create custom accounts.
  • Azure AD B2B (Business-to-Business): Enables collaboration with users from other organizations. Guest users can be invited to access resources within your tenant.

3. Choosing the Right Authentication Flow

OAuth 2.0 and OpenID Connect define several different “flows” or methods for obtaining access tokens. The appropriate flow for your mobile application depends on your specific requirements and security considerations. Here are the most relevant flows for mobile apps:

  • Authorization Code Flow with PKCE (Proof Key for Code Exchange): This is the recommended flow for native mobile applications. It’s the most secure option and is specifically designed to mitigate security risks associated with mobile environments. Here’s how it works:

    1. Authorization Request: The app redirects the user to the Microsoft identity platform’s authorization endpoint, including parameters like the client_id, redirect_uri, scope, and a code_challenge (generated using a cryptographically secure random string and a hashing algorithm).
    2. User Authentication: The user authenticates with the Microsoft identity platform (e.g., by entering their username and password).
    3. Authorization Code Grant: If authentication is successful, the identity platform redirects the user back to the app’s redirect_uri with an authorization_code in the query parameters.
    4. Token Request: The app makes a back-channel request (directly to the Microsoft identity platform’s token endpoint, not through the user’s browser) to exchange the authorization_code for an access_token, id_token, and optionally a refresh_token. This request includes the client_id, redirect_uri, authorization_code, and a code_verifier (the original random string used to generate the code_challenge).
    5. Token Response: The identity platform verifies the code_verifier against the previously stored code_challenge and, if valid, issues the tokens.

    PKCE (Proof Key for Code Exchange) is a crucial security extension to the Authorization Code Flow. It prevents attackers from intercepting the authorization_code and exchanging it for tokens, even if they can intercept the redirect. This is because the attacker won’t know the code_verifier, which is only known to the app and the identity platform.

  • Implicit Flow: This flow was previously common for single-page applications (SPAs) and mobile apps, but it’s no longer recommended due to security vulnerabilities. In the implicit flow, the access token and ID token are returned directly in the URL fragment after the user authenticates. This makes the tokens susceptible to interception, especially in mobile environments where custom URI schemes can be more easily exploited. Avoid using the Implicit Flow.

  • Resource Owner Password Credentials (ROPC) Flow: This flow involves the application directly collecting the user’s username and password and exchanging them for tokens. This flow is strongly discouraged for most scenarios, as it requires the application to handle user credentials directly, increasing the risk of security breaches. ROPC should only be used in highly trusted scenarios where other flows are not feasible (e.g., legacy applications).

4. Setting Up Your Application in Microsoft Entra ID

Before you can start coding, you need to register your mobile application with Microsoft Entra ID. This process creates an application object that represents your app within the identity platform and allows you to configure authentication settings.

  1. Sign in to the Azure Portal: Go to portal.azure.com and sign in with your Microsoft account (work or school account, or a personal Microsoft account).

  2. Navigate to Microsoft Entra ID: In the left-hand navigation pane, find and select “Microsoft Entra ID” (or search for it).

  3. App Registrations: In the Microsoft Entra ID blade, select “App registrations.”

  4. New Registration: Click “+ New registration.”

  5. Register an Application:

    • Name: Enter a descriptive name for your application (this is displayed to users during the consent process).
    • Supported account types: Choose the appropriate option based on your target audience:
      • Accounts in this organizational directory only (Single tenant): For applications that are only intended for users within your organization.
      • Accounts in any organizational directory (Any Microsoft Entra directory – Multitenant): For applications that can be used by users from any Microsoft Entra tenant.
      • Accounts in any organizational directory (Any Microsoft Entra directory – Multitenant) and personal Microsoft accounts (e.g. Skype, Xbox): For applications that can be used by both organizational users and users with personal Microsoft accounts.
      • Personal Microsoft accounts only: For application used by users with a personal Microsoft Account.
    • Redirect URI: This is crucial for mobile applications. You’ll need to use a custom URI scheme that your app can handle. The format typically looks like this:

      • Android: msal{YOUR_CLIENT_ID}://auth (e.g., msal12345678-9abc-def0-1234-56789abcdef0://auth)
      • iOS: msal{YOUR_CLIENT_ID}://auth (e.g., msal12345678-9abc-def0-1234-56789abcdef0://auth)
      • Xamarin/MAUI: Follow platform specific guidelines. Often uses a similar format to iOS/Android
      • React Native/Flutter: Follow platform and library specific guidelines.

      Important: The redirect_uri you enter here must match the one you configure in your mobile application code. Also, make sure your app is configured to handle this custom URI scheme (see platform-specific instructions below).

  6. Click “Register”: This creates your application registration.

  7. Record the Client ID (Application ID): After registration, you’ll be taken to the application overview page. Make a note of the “Application (client) ID.” You’ll need this ID in your mobile application code.

  8. Configure Platform Settings (Optional but Recommended): For a better user experience and to enable certain features (like broker-based authentication), it’s recommended to configure platform-specific settings.

    • Go to “Authentication” under “Manage” in your app registration.
    • Click “+ Add a platform.”
    • Choose “Mobile and desktop applications.”
    • Enter your redirect_uri again (it should be pre-filled). You may need to configure additional settings depending on the platform (see platform-specific sections below).
  9. API Permissions (Optional):
    If your application needs to access other Microsoft APIs (like Microsoft Graph), you need to configure API permissions.

    • Go to “API permissions” under “Manage”.
    • Click “+ Add a permission.”
    • Select the API you want to access (e.g., “Microsoft Graph”).
    • Choose the type of permissions:
      • Delegated permissions: The app accesses the API on behalf of the signed-in user. This is the most common type for mobile apps.
      • Application permissions: The app accesses the API with its own identity, without a signed-in user. This is typically used for background services or daemons.
    • Select the specific permissions you need (e.g., User.Read, Mail.Send).
    • Click “Add permissions.”
    • Depending on the permissions you choose, you may need administrator consent.

5. Platform-Specific Implementations

Now, let’s delve into the implementation details for different mobile platforms, focusing on using the Microsoft Authentication Library (MSAL). MSAL significantly simplifies the authentication process by handling token acquisition, caching, and renewal.

5.1 Android

Prerequisites:

  • Android Studio
  • Android SDK (API level 16 or higher)
  • A registered application in Microsoft Entra ID (as described in Section 4)

Steps:

  1. Add MSAL Dependency: In your app’s build.gradle (Module: app) file, add the MSAL dependency:

    gradle
    dependencies {
    implementation 'com.microsoft.identity.client:msal:4.+' // Use the latest version
    }

    Sync your project with Gradle files.

  2. Configure Redirect URI: In your AndroidManifest.xml file, add an intent-filter to handle your custom URI scheme. This tells Android that your app should be launched when a URL with that scheme is encountered.

    “`xml




    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data
            android:scheme="msal{YOUR_CLIENT_ID}"
            android:host="auth" />
    </intent-filter>
    


    “`

    Replace {YOUR_CLIENT_ID} with your actual Client ID.

  3. Create MSAL Configuration: Create a JSON configuration file (e.g., auth_config.json) in your res/raw directory. This file will contain your application’s configuration settings.

    json
    {
    "client_id" : "{YOUR_CLIENT_ID}",
    "authorization_user_agent" : "DEFAULT",
    "redirect_uri" : "msal{YOUR_CLIENT_ID}://auth",
    "account_mode" : "SINGLE",
    "broker_redirect_uri_registered": false,
    "authorities" : [
    {
    "type": "AAD",
    "audience": {
    "type": "AzureADandPersonalMicrosoftAccount",
    "tenant_id": "common"
    }
    }
    ]
    }

    * client_id: Your application’s Client ID.
    * redirect_uri: Your custom redirect URI.
    * account_mode: Set to “SINGLE” if you want to support only a single account at a time, “MULTIPLE” for multiple accounts
    * broker_redirect_uri_registered: If set to true, MSAL library will use the broker. Set this to true if you intend to leverage the Microsoft Authenticator app or Intune Company Portal for SSO and device compliance.
    * authorities: Specifies the identity providers you want to support. "tenant_id": "common" allows sign-in from any Microsoft Entra tenant or personal Microsoft accounts. You can also use your tenant ID for single-tenant applications.

  4. Initialize MSAL: In your MainActivity (or your main activity), initialize MSAL:
    “`java
    import com.microsoft.identity.client.;
    import com.microsoft.identity.client.exception.
    ;

    public class MainActivity extends AppCompatActivity {
    
        private ISingleAccountPublicClientApplication mSingleAccountApp;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            PublicClientApplication.createSingleAccountPublicClientApplication(this.getApplicationContext(),
                    R.raw.auth_config,
                    new IPublicClientApplication.ISingleAccountApplicationCreatedListener() {
                        @Override
                        public void onCreated(ISingleAccountPublicClientApplication application) {
                            mSingleAccountApp = application;
                        }
    
                        @Override
                        public void onError(MsalException exception) {
                            // Handle error
                            Log.e("MSAL", "Error initializing MSAL", exception);
                        }
                    });
        }
    

    }

    “`

  5. Acquire a Token Interactively (Sign In):
    “`java
    private void signIn() {
    if (mSingleAccountApp == null) {
    return;
    }

    mSingleAccountApp.signIn(this, null, new String[]{"User.Read"}, getAuthInteractiveCallback());
    

    }
    “`

    The signIn method initiates the interactive sign-in flow. new String[]{"User.Read"} specifies the scopes (permissions) you are requesting. getAuthInteractiveCallback() is a callback function that handles the result of the authentication attempt.

  6. Implement the Interactive Callback:
    “`java
    private AuthenticationCallback getAuthInteractiveCallback() {
    return new AuthenticationCallback() {

        @Override
        public void onSuccess(IAuthenticationResult authenticationResult) {
            // Successfully acquired token
            String accessToken = authenticationResult.getAccessToken();
            // Use the access token to call Microsoft Graph or other APIs
            // Update UI
             Log.d("MSAL", "Access token acquired: " + accessToken);
        }
    
        @Override
        public void onError(MsalException exception) {
            // Authentication failed
            Log.e("MSAL", "Authentication failed", exception);
        }
    
        @Override
        public void onCancel() {
            // User cancelled the flow
            Log.d("MSAL", "User cancelled the sign in.");
        }
    };
    

    }

    ``
    7. **Handle the Redirect:**
    Override
    onActivityResult` in your activity to handle the redirect from the Microsoft identity platform:

java
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (mSingleAccountApp != null) {
mSingleAccountApp.handleInteractiveRequestRedirect(requestCode, resultCode, data);
}
}

8. Acquire a Token Silently:

After the user has signed in once, you can attempt to acquire tokens silently (without user interaction) using the acquireTokenSilentAsync method:

```java
private void acquireTokenSilently() {
    if (mSingleAccountApp == null) {
        return;
    }

    mSingleAccountApp.getCurrentAccountAsync(new ISingleAccountPublicClientApplication.CurrentAccountCallback() {
        @Override
        public void onAccountLoaded(@Nullable IAccount activeAccount) {
            if (activeAccount != null) {
               mSingleAccountApp.acquireTokenSilentAsync(new String[]{"User.Read"}, activeAccount.getAuthority(), getAuthSilentCallback());
            } else {
                //No account
            }
        }

        @Override
        public void onAccountChanged(
                @Nullable IAccount priorAccount, @Nullable IAccount currentAccount) {
            // Handle account change
        }

        @Override
        public void onError(@NonNull MsalException exception) {
              Log.e("MSAL", "Error getting current account", exception);
        }
    });
}


private AuthenticationCallback getAuthSilentCallback() {
    return new AuthenticationCallback() {
        @Override
        public void onSuccess(IAuthenticationResult authenticationResult) {
          String accessToken = authenticationResult.getAccessToken();
        }

        @Override
        public void onError(MsalException exception) {
          if (exception instanceof MsalUiRequiredException) {
              signIn(); // Fallback to interactive flow
            }
        }

        @Override
        public void onCancel() {
           //
        }
    };
}
```

If silent acquisition fails (e.g., the refresh token has expired or the user has revoked consent), you should fall back to the interactive flow (`signIn`).  `MsalUiRequiredException` indicates that user interaction is needed.
  1. Sign Out:

    “`java
    private void signOut() {
    if (mSingleAccountApp == null) {
    return;
    }

    mSingleAccountApp.signOut(new ISingleAccountPublicClientApplication.SignOutCallback() {
        @Override
        public void onSignOut() {
            // Update UI
        }
    
        @Override
        public void onError(@NonNull MsalException exception) {
           // Handle error
           Log.e("MSAL", "Sign out failed.", exception);
        }
    });
    

    }
    ``
    10. **Calling Microsoft Graph (Example):**
    After you have obtained an access token, you can use it to call Microsoft Graph. Here's a simple example using the
    OkHttp` library:

    ```java
     private void callMicrosoftGraph(String accessToken) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://graph.microsoft.com/v1.0/me") // Get the user's profile
                .addHeader("Authorization", "Bearer " + accessToken)
                .build();
    
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // Handle error
            }
    
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String responseBody = response.body().string();
                    // Parse the JSON response and display user information
                } else {
                    // Handle error
                }
            }
        });
    }
    
    ```
    

5.2 iOS

Prerequisites:

  • Xcode
  • CocoaPods (for dependency management)
  • A registered application in Microsoft Entra ID (as described in Section 4)

Steps:

  1. Add MSAL Dependency (using CocoaPods): In your project directory, create a Podfile (if you don’t have one already) and add the MSAL dependency:

    “`ruby
    platform :ios, ‘13.0’ # Use the appropriate iOS version
    use_frameworks!

    target ‘YourAppName’ do
    pod ‘MSAL’, ‘~> 1.0’ #Use latest
    end
    “`

    Then, run pod install in your terminal to install the dependency. Open the .xcworkspace file (not the .xcodeproj file) to work on your project.

  2. Configure Redirect URI:

    • Info.plist: In your project’s Info.plist file, add a URL scheme for your app. This is how the Microsoft identity platform will redirect back to your app after authentication.

      xml
      <key>CFBundleURLTypes</key>
      <array>
      <dict>
      <key>CFBundleURLSchemes</key>
      <array>
      <string>msal{YOUR_CLIENT_ID}</string>
      </array>
      </dict>
      </array>

      Replace {YOUR_CLIENT_ID} with your actual Client ID.

    • Entitlements.plist
      You need to add Keychain Sharing capability.

  3. Configure MSAL: Create a configuration object for MSAL. You can do this directly in your code or load it from a configuration file.

    “`swift
    import MSAL

    let kClientID = “{YOUR_CLIENT_ID}”
    let kAuthority = “https://login.microsoftonline.com/common” // Or your tenant ID
    let kRedirectUri = “msal(kClientID)://auth”

    var applicationContext : MSALPublicClientApplication?

    func initMSAL() {
    do{
    let authority = try MSALAADAuthority(url: URL(string: kAuthority)!)
    let msalConfiguration = MSALPublicClientApplicationConfig(clientId: kClientID, redirectUri: kRedirectUri, authority: authority)
    self.applicationContext = try MSALPublicClientApplication(configuration: msalConfiguration)
    }
    catch{
    print(“Error initializing msal (error)”)
    }
    }
    “`

  4. Acquire a Token Interactively (Sign In):

    “`swift
    func signIn() {
    guard let applicationContext = applicationContext else { return }

    let webViewParameters = MSALWebviewParameters(authPresentationViewController: self)
    let parameters = MSALInteractiveTokenParameters(scopes: ["user.read"], webviewParameters: webViewParameters)
    
    applicationContext.acquireToken(with: parameters) { (result, error) in
      if let error = error {
            print("Could not acquire token: \(error)")
            return
        }
    
        guard let result = result else {
            print("Could not acquire token: No result returned")
            return
        }
    
        let accessToken = result.accessToken
        print("Access token: \(accessToken)")
       // Call Graph API
    }
    

    }

    ``
    This starts the interactive sign-in flow, opening a web view for the user to authenticate.
    [“user.read”]` specifies the requested scopes.

  5. Handle the Redirect:

    In your SceneDelegate.swift (or AppDelegate.swift if you’re not using SwiftUI), implement the application(_:open:options:) method to handle the redirect from the Microsoft identity platform:
    “`swift
    // SceneDelegate.swift
    func scene(_ scene: UIScene, openURLContexts URLContexts: Set) {

        guard let urlContext = URLContexts.first else {
            return
        }
    
        let url = urlContext.url
        let sourceApp = urlContext.options.sourceApplication
    
        MSALPublicClientApplication.handleMSALResponse(url, sourceApplication: sourceApp)
    

    }

    “`

  6. Acquire a Token Silently:

    “`swift
    func acquireTokenSilently() {

    guard let applicationContext = applicationContext else { return }
    
    let currentAccount = applicationContext.allAccounts().first
    
    guard let account = currentAccount else {
        return
    }
    let parameters = MSALSilentTokenParameters(scopes: ["user.read"], account: account)
    applicationContext.acquireTokenSilent(with: parameters) { (result, error) in
    
        if let error = error {
    
            let nsError = error as NSError
    
            if (nsError.domain == MSALErrorDomain) {
    
                if (nsError.code == MSALError.interactionRequired.rawValue) {
    
                    DispatchQueue.main.async {
                        self.signIn() //call interactive
                    }
                    return
                }
            }
             print("Could not acquire token silently: \(error)")
            return
        }
        guard let result = result else {
            print("Could not acquire token: No result returned")
            return
        }
        let accessToken = result.accessToken
          print("Refreshed Access token: \(accessToken)")
    }
    

    }
    “`

    This attempts to acquire a token silently using the cached refresh token. If it fails with an interactionRequired error, you should fall back to the interactive flow.

  7. Sign Out:
    “`swift
    func signOut() {

      guard let applicationContext = applicationContext else { return }
    
      guard let account = applicationContext.allAccounts().first else { return }
    
     do {
    
       try applicationContext.remove(account)
         //Update UI
    
     } catch let error as NSError {
    
         print("Received error signing account out: \(error)")
     }
    

    }

    8. **Calling Graph API:**swift
    func callGraphAPI(accessToken: String){
    guard let url = URL(string: “https://graph.microsoft.com/v1.0/me”) else {return}
    var request = URLRequest(url: url)
    request.setValue(“Bearer (accessToken)”, forHTTPHeaderField: “Authorization”)
    URLSession.shared.dataTask(with: request) { data, response, error in

            if let error = error {
                print("Error calling Graph: \(error.localizedDescription)")
                return
            }
    
             guard let data = data else {
                print("No data returned from Graph")
                return
            }
    
            do {
                //Parse
                let profile = try JSONSerialization.jsonObject(with: data, options: [])
                print(profile)
              } catch {
                  print("JSON error")
              }
    
        }.resume()
    }
    

    “`

5.3 Xamarin/MAUI (.NET)

Prerequisites:

  • Visual Studio (with Xamarin or MAUI workload installed)
  • A registered application in Microsoft Entra ID

Steps:
MSAL.NET is used for Xamarin and MAUI.

  1. Install MSAL NuGet Package: In your Visual Studio project, right-click on the solution and select “Manage NuGet Packages for Solution…” Search for Microsoft.Identity.Client and install it in all relevant projects (shared project, Android project, iOS project).

  2. Configure Platform-Specific Settings:

    • Android: Follow the same steps as the native Android implementation (Section 5.1, steps 2 and 7) to configure the AndroidManifest.xml and handle the redirect in your MainActivity.
    • iOS: Follow the same steps as the native iOS implementation (Section 5.2, steps 2 and 5) to configure Info.plist, add Keychain Sharing and handle the redirect in your AppDelegate.
  3. Create MSAL Configuration:

“`csharp
public static string ClientId = “{YOUR_CLIENT_ID}”;
public static string[] Scopes = { “User.Read” };
public static string Authority = “https://login.microsoftonline.com/common”; // Or your tenant ID
public static string RedirectUri = “msal{YOUR_CLIENT_ID}://auth”;

    public static IPublicClientApplication PublicClientApp { get; private set; }

“`
4. Initialize MSAL:

```csharp
    // In your shared code (e.g., App.xaml.cs)
     PublicClientApp = PublicClientApplicationBuilder.Create(ClientId)
                    .WithAuthority(Authority)
                    .WithRedirectUri(RedirectUri)
                    .WithIosKeychainSecurityGroup("com.microsoft.adalcache") // iOS only
                    .Build();
 //For Android you need to pass the activity
 //  .WithParentActivityOrWindow(() => Platform.CurrentActivity) // Add this for Android
```
  1. Acquire a Token Interactively (Sign In):

    csharp
    public async Task<AuthenticationResult> SignInAsync()
    {
    AuthenticationResult authResult = null;
    try
    {
    authResult = await PublicClientApp.AcquireTokenInteractive(Scopes)
    .WithParentActivityOrWindow(Platform.CurrentActivity) //Android only
    .ExecuteAsync();
    }
    catch (MsalException ex)
    {
    // Handle errors
    }
    return authResult;
    }

  2. Acquire a Token Silently:

    “`csharp
    public async Task AcquireTokenSilentAsync()
    {
    AuthenticationResult authResult = null;
    try
    {
    var accounts = await PublicClientApp.GetAccountsAsync();
    authResult = await PublicClientApp.AcquireTokenSilent(Scopes, accounts.FirstOrDefault())
    .ExecuteAsync();
    }
    catch (MsalUiRequiredException ex)
    {
    // A MsalUiRequiredException happened on AcquireTokenSilent.
    // This indicates you need to call AcquireTokenInteractive to acquire a token
    authResult = await SignInAsync(); //call interactive

        }
        catch (Exception ex)
        {
           // Handle errors
        }
         return authResult;
    }
    

    ``
    If silent acquisition fails with
    MsalUiRequiredException, callSignInAsync` to initiate the interactive flow.

  3. Sign Out:
    “`csharp
    public async Task SignOutAsync()
    {
    var accounts = await PublicClientApp.GetAccountsAsync();

        while (accounts.Any())
        {
            await PublicClientApp.RemoveAsync(accounts.FirstOrDefault());
            accounts = await PublicClientApp.GetAccountsAsync();
        }
    }
    

    “`

  4. Call Graph API:
    “`csharp
    public async Task GetUserProfile(string accessToken)
    {
    using (var client = new HttpClient())
    {
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(“Bearer”, accessToken);
    var response = await client.GetAsync(“https://graph.microsoft.com/v1.0/me”);

          if (response.IsSuccessStatusCode)
            {
                return await response.Content.ReadAsStringAsync();
            }
          return "";
        }
    }
    

    “`

5.4 React Native

Prerequisites:

  • Node.js and npm (or yarn)
  • React Native CLI
  • A registered application in Microsoft Entra ID

Steps:

There are several libraries available for integrating Microsoft Authentication with React Native. react-native-msal and @azure/msal-react-native are popular options, though @azure/msal-react-native is the newer, officially supported one. However, it is a wrapper around the native MSAL libraries, so you still need to do some platform-specific setup. We’ll focus on @azure/msal-react-native here.

  1. Install Dependencies:

    “`bash
    npm install @azure/msal-react-native @azure/msal-common

    or

    yarn add @azure/msal-react-native @azure/msal-common
    “`
    2. Platform-Specific Setup (Android):

    • AndroidManifest.xml: Add the intent-filter for

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top