Microsoft Authentication Library (MSAL) for .NET

repository·main·Indexed 23 days ago

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

A security library used to acquire security tokens from the Microsoft identity platform (formerly Azure AD) and Azure AD B2C to call protected APIs using OAuth2 and OpenID Connect. It provides the Microsoft.Identity.Client NuGet package and supports advanced scenarios including Client-Assertion APIs for confidential clients, mTLS Proof-of-Possession (PoP), and experimental cache key extensibility via WithAdditionalCacheKeyComponents.

Tokens
29K
Snippets
40
Records
129
Agent score
81%

What's inside MSAL.NET

  1. Overview of the Managed Identity SLC Prototype Demo workflow

    main

    This prototype demonstrates an experimental Managed-Identity flow using MSAL to handle certificate rotation and token acquisition against a prototype SLC endpoint. The workflow follows these steps:

    1. Identity Detection: Detects the Managed-Identity source (expected to be Credential when the SLC endpoint is live).
    2. Certificate Creation: Creates an in-memory binding certificate (e.g., CN=devicecert.mtlsauth.local).
    3. Certificate Rotation: MSAL raises the BindingCertificateUpdated event whenever it generates a fresh certificate (the prototype uses a 7-day lifetime).
    4. Token Exchange: Calls the SLC /credential endpoint via mTLS to exchange the credential for an AAD access token (using the default scope https://vault.azure.net/).
  2. Understand MSI v2 Key Management

    main

    In MSI v2, MSAL requires an asymmetric RSA key pair to interact with managed identity endpoints (such as the Instance Metadata Service (IMDS) or the ESTS token service). This private key serves as the local root of trust for several critical security operations:

    • CSR generation: Creating Certificate Signing Requests.
    • Certificate issuance: Facilitating the issuance of certificates.
    • Proof-of-Possession (PoP) binding: Binding tokens to the key.
    • mTLS handshakes: Performing mutual TLS handshakes.

    The key management layer handles the generation, storage, and protection of these keys, ensuring they are stored in the most secure manner supported by the host platform.

  3. Security requirements for MSI v2 private keys

    main

    To maintain security when handling MSI v2 certificates on Windows, follow these requirements:

    • Key Generation: Private keys must be generated in CNG/KeyGuard.
    • Export Policy: Set ExportPolicy = None. Keys should never be exported or persisted outside of the Windows certificate store.
    • Scope: Use the CurrentUser\My store to ensure the certificate is scoped strictly to the signed-in user.
  4. Configure multiple Client Capabilities

    main

    The WithClientCapabilities method accepts an array of capabilities. When multiple capabilities are provided, they are passed to the Resource Provider (RP) as a comma-separated list in the xms_cc query parameter, which must be URL-encoded.

    Format: xms_cc=cp1,cp2,cp3

    RP Implementation Note: RPs must URL-decode this parameter and split the string by commas to identify the individual capabilities. If the CAE capability (cp1) is present, the RP MUST pass it through.

  5. How MSAL.NET performs region auto-discovery

    main

    MSAL.NET automatically discovers the Azure region to optimize authentication requests. The discovery process follows a strict hierarchy of precedence. If a discovery step succeeds, the result is cached process-wide for the lifetime of the application to avoid repeated IMDS calls.

    Discovery Order:

    1. REGION_NAME environment variable: If this variable is set and well-formed, it takes highest precedence.
    2. IMDS /compute JSON call: MSAL attempts to call the Azure Instance Metadata Service (IMDS) endpoint using api-version=2021-02-01 to retrieve the location field from a JSON response.
    3. API-version probe: If the IMDS call returns a 400 Bad Request, MSAL probes the endpoint without an api-version to find the newest-versions and retries with that version.
    4. Fallback: If all IMDS attempts fail, MSAL caches the failure and falls back to the global ESTS endpoint.
  6. Understand the RevoGuard Managed Identity (MSI) Token Revocation Workflow

    main

    RevoGuard is a sandbox environment designed to test the revocation of Managed Identity (MSI) tokens. The workflow allows developers to validate how Azure resources and applications behave when presented with revoked or invalidated tokens.

    The workflow follows these stages:

    1. Token Acquisition: The Managed Identity Host requests a token from the Azure AD (Entra ID) via the local MSI/IMDS endpoint. The host then uses this token to access a Target Resource.
    2. Revocation: A revocation action is performed via the RevoGuard mechanism to invalidate the token in Azure AD.
    3. Validation Failure: The Host attempts to use the old token, and the Target Resource must deny access based on the updated revocation status.
    4. Recovery: The Host requests a fresh token from the MSI/IMDS endpoint and successfully accesses the Target Resource with the new token.

    This process is used to measure the latency between a revocation action and the moment a resource begins rejecting the invalidated token.

    sequenceDiagram
        participant AAD as Azure AD (Entra ID)
        participant Host as Managed Identity Host
        participant Resource as Target Resource
        participant Revo as Revocation Mechanism
        participant Monitor as Monitoring & Logging
    
        rect rgb(245, 245, 245)
        Note over Host: 1) Host requests MSI token
        Host->>AAD: Request token (MSI/IMDS endpoint)
        AAD-->>Host: Returns short-lived access token
        Host->>Resource: Presents access token
        Resource-->>Host: Access granted
        end
    
        rect rgb(245, 245, 245)
        Note over Revo: 2) Revoke token via RevoGuard
        Revo->>AAD: Revocation action (invalidate token)
        AAD-->>Resource: Updated revocation status
        Host->>Resource: Attempts to use old token
        Resource-->>Host: Access denied (revoked token)
        end
    
        rect rgb(245, 245, 245)
        Note over Monitor: 3) Observe logs & metrics
        Monitor->>AAD: Collect sign-in & token logs
        Monitor->>Resource: Collect access & denial events
        end
    
        rect rgb(245, 245, 245)
        Note over Host: 4) Host acquires new token & retries
        Host->>AAD: Request new token (MSI/IMDS endpoint)
        AAD-->>Host: Returns fresh short-lived token
        Host->>Resource: Presents new valid token
        Resource-->>Host: Access granted (new token)
        end
  7. Understand MSAL behavior for claims challenges and unspecified credential issues

    main

    MSAL handles several other credential and authorization scenarios automatically:

    • Claims Challenge: If a Resource returns a 401 with claims, MSAL will re-mint the certificate using bypass_cache=true and retry the request including the required claims. This results in a CredentialOutcome=Success.
    • Unspecified Credential Issue: If the eSTS returns invalid_client but does not provide specific error_codes, MSAL treats this as a remediable issue. It will force a new certificate via bypass_cache=true and retry until success. This results in a CredentialOutcome=Retry Succeeded.
    • IssueCredential Failure: If the call to /issuecredential fails due to network, service, or malformed request issues, MSAL returns the failure. The retry behavior for these transport-level failures follows standard MSAL retry logic.
  8. Understand the MSAL custom cache key schema

    main

    When using WithAdditionalCacheKeyComponents, MSAL modifies the access token cache key using a specific deterministic algorithm. This ensures that lookups are consistent and case-sensitive.

    Key Generation Logic:

    1. The key-value pairs are ordered alphabetically by key.
    2. The pairs are concatenated (e.g., key1val1key2val2).
    3. The resulting string is hashed using SHA256.
    4. This hash is appended as a suffix to the standard cache key.

    Example: If you provide {"key1": "val1", "key2": "val2"}, the suffix will be the SHA256 hash of key1val1key2val2.

    Important Behavior:

    • Lookups are ordinal case sensitive. Using Key1 instead of key1 will result in a cache miss.
    • Only access tokens are affected by this new schema in user flows. Refresh tokens and ID tokens remain shared and do not use this extended keying logic.
  9. Understand the MSAL.NET support lifecycle and upgrade requirements

    main

    MSAL.NET support is governed by three key principles that dictate when you must upgrade your dependencies to remain secure:

    1. Last Major Release Support Window: When a new major version (e.g., v8.0) is released, only the latest patch release of the previous major version (e.g., v7.7.1) remains supported for a grace period of 180 days.
    2. Deprecation of Older Versions: Upon the release of a new major version, all previous minor and patch versions of the preceding major version (except for the final patch release) are immediately deprecated. For example, if v8.0.0 is released, all versions from v7.0.0 up to v7.7.0 are deprecated. You should upgrade to the final patch of the old branch (v7.7.1) or move to the new major branch (v8.x).
    3. Security Fixes Only in Supported Versions: Security and critical bug fixes are not back-ported to deprecated patch versions. If a vulnerability is discovered, you must upgrade to the currently supported version (the latest major or the final patch of the previous major during its 180-day overlap) to receive the fix.
  10. Understand MSAL.NET version support and lifecycle

    main

    MSAL.NET follows a specific support lifecycle. It is critical to stay updated to ensure security and feature enhancements.

    • Major Versions: Supported for twelve months after the release of the next major version.
    • Minor Versions: Only the latest two minor versions (N and N-1) are supported. Older minor versions will not receive bug fixes or security patches.
    • Security Recommendation: Always use the latest minor version (e.g., x.*y*.z) to receive security enhancements without breaking your API surface, as the library follows semantic versioning.
  11. How FMI credential acquisition works in MSAL

    main

    FMI (Federated Managed Identity) credential acquisition is a specialized flow where MSAL handles the low-level HTTP logic to retrieve a credential from an endpoint defined by the APP_IDENTITY_ENDPOINT environment variable.

    Instead of the consumer manually handling HTTP requests to fetch these credentials, MSAL's Managed Identity implementation intercepts requests for the specific FMI resource (api://AzureFMITokenExchange/.default). MSAL then crafts the request based on the FMI environment variables present on the machine. The resulting authentication object contains both the credential and its expiration, which can then be used as a client assertion for other MSAL applications.

    Key characteristics:

    • Resource-Triggered: The flow is triggered implicitly by requesting the FMI-specific resource URI.
    • No Caching: Tokens acquired through this flow are not cached by MSAL; the consumer (e.g., MISE) is expected to receive a new token each time the flow is used.
    • Experimental: This functionality is intended for specific integrations and is gated behind the experimental features flag.
  12. Compare Managed Identity mTLS PoP vs. Confidential Client mTLS PoP

    main

    MSAL supports two distinct mTLS PoP flows. Choose the one that matches your authentication method:

    FeatureManaged Identity (IMDSv2)
    Certificate ProviderIMDS mints it automatically
    API Entry PointAcquireTokenForManagedIdentity().WithMtlsProofOfPossession()
    Region Required?No (endpoint comes from IMDS response)
    PlatformWindows only
    CSR FlowYes (multi-step: metadata → CSR → cert issuance)
    FeatureConfidential Client (SNI cert)
    Certificate ProviderYou provide it via .WithCertificate()
    API Entry PointAcquireTokenForClient().WithMtlsProofOfPossession()
    Region Required?Yes — .WithAzureRegion("region") required
    PlatformCross-platform
    CSR FlowNo (cert already in hand)