Microsoft Authentication Library (MSAL) for Android

repository·dev·Indexed 42 days ago

https://github.com/azuread/microsoft-authentication-library-for-android

MSAL for Android enables developers to authenticate users and access secured web APIs using the Microsoft identity platform, supporting Azure AD, personal Microsoft accounts, and Azure AD B2C. The library provides support for both Single Account and Multiple Account modes, silent token acquisition, and broker integration for SSO. It requires Android SDK 16+ and supports Java 1.8.

Tokens
18.6K
Snippets
31
Records
68
Agent score
53%

What's inside MSAL

  1. Introduction to MSAL for Android

    dev

    The Microsoft Authentication Library (MSAL) for Android allows developers to acquire security tokens from the Microsoft identity platform. This enables user authentication and access to secured web APIs in Android applications.

    Key capabilities include:

    • Support for Microsoft Azure Active Directory and Microsoft Personal Accounts using OAuth2 and OpenID Connect.
    • Support for Azure AD B2C.
    • Access to the Microsoft Cloud.
  2. Overview of MSAL and Common Android libraries

    dev

    The Microsoft Authentication Library (MSAL) for Android is composed of two primary packages:

    1. com.microsoft.identity.client.msal: The main MSAL library used by developers to perform authentication tasks.
    2. com.microsoft.identity.common: A supporting library that provides abstractions and identity provider-specific implementations. MSAL depends on this common library.

    Developers should primarily interact with the com.microsoft.identity.client.msal package to integrate authentication into their Android applications.

  3. What is Proof of Possession (PoP)?

    dev

    Proof of Possession (PoP) is a security enhancement for access tokens. While standard Bearer tokens can be used by anyone in possession of them, PoP tokens are bound to a unique RSA key pair generated on the device.

    The client uses this key to sign the request, creating a Signed HTTP Request (SHR). This binding ensures that the token is unusable without the corresponding private key residing on the original device, protecting against token replay attacks.

  4. How the Command Dispatcher manages API calls

    dev

    The CommandDispatcher is the central engine that manages the lifecycle of an API request. When a command is submitted, the dispatcher performs the following tasks:

    • Duplicate Detection: It determines if the exact same command is already executing. If so, it throws a duplicate command exception.
    • Thread Management: It executes commands in specific thread pools based on their type. For example:
      • Interactive commands: These are serialized (executed one after another).
      • Silent commands: These are run in parallel.
    • Result Caching: It checks a CommandResultCache which stores results from prior executions for up to 30 seconds to reduce service load.
    • Execution & Notification: It executes the command, caches the result, and notifies the caller via the callback provided within the command.
  5. How Single Account Mode works in MSAL

    dev

    Single Account Mode restricts the application to using only one account at a time. This is ideal for apps where a user session is strictly tied to a single identity.

    Core Workflow:

    1. Initialization: Use PublicClientApplication.createSingleAccountPublicClientApplication.
    2. Sign In: Use signIn(SignInParameters) for the initial login. You can also use signInAgain(SignInParameters) to force re-authentication.
    3. Account Monitoring: Use getCurrentAccountAsync(...) to check if a user is already signed in. The onAccountChanged callback allows you to react to account switches.
    4. Silent Acquisition: Similar to multiple account mode, use acquireTokenSilentAsync to refresh tokens in the background.
    5. Sign Out: Use signOut(...) to clear the single active account.
    // Initialization
    PublicClientApplication.createSingleAccountPublicClientApplication(
        context,
        R.raw.auth_config,
        new PublicClientApplication.ISingleAccountApplicationCreatedListener() {
            @Override
            public void onCreated(ISingleAccountPublicApplication application) {
                mSingleAccountApp = application;
            }
            @Override
            public void onError(MsalException exception) { /* Handle error */ }
        }
    );
    
    // Sign In
    SignInParameters parameters = SignInParameters.builder()
        .withScopes(scopes)
        .withActivity(activity)
        .withCallback(getAuthInteractiveCallback())
        .build();
    
    mSingleAccountApp.signIn(parameters);
  6. MSALOAuth2TokenCache implementation details

    dev

    The MSALOAuth2TokenCache is the standard cache implementation used by MSAL.

    Key Characteristics:

    • Instance Scope: There is exactly one instance of this cache per PublicClientApplication created within an Android application.
    • Identification: The cache is identified by its client_id.

    Special Case: Microsoft Family of Client IDs Applications published by Microsoft may be authorized to share refresh tokens. These applications share a single MSALOAuth2TokenCache instance. Even though each application has its own unique Microsoft Identity platform client ID, the cache for this family uses "1" as the client ID by convention.

  7. Request specific claims in id_token and userinfo responses

    dev

    MSAL allows you to request specific claims to be included in the id_token and userinfo endpoint responses. This is achieved by creating and serializing a ClaimsRequest object. This mechanism follows the OpenID Connect specification for the claims request parameter.

    Key classes involved:

    • ClaimsRequest: The primary object used for creating and serializing claims requests.
    • RequestedClaim: Represents an individual claim being requested.
    • RequestedClaimAdditionalInformation: Used to provide extra context or parameters for a specific requested claim.
  8. How Multiple Account Mode works in MSAL

    dev

    Multiple Account Mode (the default) allows your application to manage and switch between several authenticated accounts.

    Core Workflow:

    1. Initialization: Use PublicClientApplication.createMultipleAccountPublicClientApplication passing your context and the raw resource ID of your config file.
    2. Interactive Sign-In: Use acquireToken(AcquireTokenParameters) to trigger an interactive login flow. This requires an Activity to start the authorization.
    3. Account Management: Use getAccounts() to retrieve a list of currently signed-in accounts. Use removeAccount(IAccount, ...) to sign an individual account out.
    4. Silent Acquisition: Use acquireTokenSilentAsync(AcquireTokenSilentParameters) to get tokens without user interaction using a previously acquired account and its authority.
    // Initialization
    PublicClientApplication.createMultipleAccountPublicClientApplication(
        context,
        R.raw.auth_config,
        new IPublicClientApplication.IMultipleAccountApplicationCreatedListener() {
            @Override
            public void onCreated(IMultipleAccountPublicClientApplication application) {
                mMultipleAccountPCA = application;
            }
            @Override
            public void onError(MsalException exception) { /* Handle error */ }
        }
    );
    
    // Interactive Token Acquisition
    AcquireTokenParameters parameters = new AcquireTokenParameters.Builder()
        .withScopes(SCOPES)
        .startAuthorizationFromActivity(activity)
        .withCallback(getAuthInteractiveCallback())
        .build();
    
    mMultipleAccountApp.acquireToken(parameters);
  9. Understand the Universal Cache Schema entities

    dev

    The universal cache schema is composed of several key entities used to represent identity information:

    • Accounts: Represented by the ID Token of the account's home tenant.
    • Tenant Profiles: Represents a single account's presence in one or more tenants (e.g., guest or member scenarios). It includes the ID Token of the home tenant and ID Tokens from other tenants the account belongs to.
    • Credentials: The actual tokens used for authentication and authorization. This includes:
      • IdTokenRecord (ID Tokens)
      • AccessTokenRecord (Access Tokens)
      • RefreshTokenRecord (Refresh Tokens)
      • PrimaryRefreshTokenRecord (Primary Refresh Tokens)

    All credential types inherit from the Credential abstract base class, and all these entities inherit from AccountCredentialBase, which provides common functionality for appending additional information to accounts and credentials.

  10. Compare ADAL and MSAL Prompt behaviors

    dev

    If you are migrating from ADAL to MSAL, note the differences in how prompts are handled. MSAL uses more explicit naming conventions for prompt behaviors.

    ADAL PromptMSAL Equivalent / Behavior
    nullSELECT_ACCOUNT
    AutoWHEN_REQUIRED (Attempts silent request first; if unsuccessful, switches to interactive)
    AlwaysLOGIN (User is always prompted for credentials)
    FORCE_PROMPTSimilar to LOGIN (If no broker is installed, behaves like Always; if a broker is installed, a prompt for credentials is shown)
    REFRESH_SESSION(Not directly mapped to a single MSAL constant, but relates to reauthorizing the user)
  11. Select the appropriate MSAL authentication method

    dev

    MSAL for Android provides different methods for acquiring tokens depending on the device capabilities and security requirements:

    • AcquireToken: This is the recommended method for most scenarios. Use this to ensure standard authentication flows.
    • AcquireTokenWithDeviceCode: Use this only in niche scenarios where the device lacks the necessary input methods (e.g., a headless device or a device without a browser/keyboard) to support the standard AcquireToken flow. Note that Device Code Flow is generally less recommended due to industry security concerns.
  12. Understand Public Client Application types in MSAL

    dev

    In MSAL for Android, the primary interface for authentication is PublicClientApplication. Because mobile applications are considered 'public clients' (they cannot securely keep secrets), MSAL provides two distinct sub-types based on your application's requirements:

    1. Single Account Public Client Application (ISingleAccountPublicClientApplication):

      • Use this if your application only expects one account to be in use at a time.
      • Example: Line-of-business (LOB) applications.
    2. Multiple Account Public Client Application (IMultipleAccountPublicClientApplication):

      • Use this if your application needs to support multiple accounts simultaneously.
      • Example: B2C applications or email clients where users switch between different identities.