Microsoft Authentication Library (MSAL) for Java

repository·dev·Indexed 43 days ago

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

Enables Java applications to integrate with the Microsoft identity platform to sign in users or apps using Azure AD, Microsoft accounts, and Azure AD B2C. It provides tokens for calling Microsoft Graph and custom APIs. The library includes support for Managed Identity source detection, interactive flows on Linux, and extensions for secure, cross-platform token cache serialization and persistence via msal4j-persistence-extension.

Tokens
2.4K
Snippets
8
Records
12
Agent score
56%

What's inside MSAL4J

  1. How to persist MSAL Java token caches across platforms

    dev

    MSAL Java uses an in-memory cache by default. To persist this cache to disk securely, you can use the PersistenceTokenCacheAccessAspect provided by this extension. This class implements the ITokenCacheAccessAspect interface required by MSAL Java.

    The extension handles platform-specific encryption:

    • Windows: Uses DPAPI.
    • macOS: Uses the MAC Keychain (encryption is built-in).
    • Linux: Uses LibSecret. Note that encryption is only supported where libsecret is available.

    Important Recommendation: Use this library for Public client applications (e.g., Desktop apps) only. For web applications, persist the cache in the session to avoid scale and performance issues.

    // High-level pattern:
    // 1. Configure PersistenceSettings
    // 2. Create PersistenceTokenCacheAccessAspect
    // 3. Pass the aspect to PublicClientApplication.builder().setTokenCacheAccessAspect()
  2. Implement token cache persistence in a PublicClientApplication

    dev

    To integrate the persistence extension into your MSAL Java application, follow these steps:

    1. Create PersistenceSettings using the builder.
    2. Instantiate PersistenceTokenCacheAccessAspect with those settings.
    3. Use .setTokenCacheAccessAspect() when building your PublicClientApplication.

    The implementation includes built-in file locking and auto-reload behavior.

    // 1. Create settings
    private PersistenceSettings createPersistenceSettings() throws IOException {
        Path path = Paths.get(System.getProperty("user.home"), "MSAL", "testCache");
        return PersistenceSettings.builder("testCacheFile", path)
                .setMacKeychain("MsalTestService", "MsalTestAccount")
                .setLockRetry(1000, 50)
                .build();
    }
    
    // 2. Create the aspect
    private ITokenCacheAccessAspect createPersistenceAspect() throws IOException {
        return new PersistenceTokenCacheAccessAspect(createPersistenceSettings());
    }
    
    // 3. Configure the MSAL client
    return PublicClientApplication.builder(PUBLIC_CLIENT_ID)
        .authority(AUTHORITY)
        .setTokenCacheAccessAspect(createPersistenceAspect())
        .build();
  3. Install the MSAL Java Persistence Extension via Maven

    dev

    To use the Microsoft Authentication Extensions for Java, add the following dependency to your pom.xml file. This library provides secure, cross-platform token cache serialization and persistence for MSAL Java applications.

    <dependency>
        <groupId>com.microsoft.azure</groupId>
        <artifactId>msal4j-persistence-extension</artifactId>
        <version>1.2.0</version>
    </dependency>
  4. How Managed Identity source detection works

    dev

    The ManagedIdentityClient automatically detects the environment to determine the appropriate Managed Identity source. It uses specific environment variables to distinguish between different Azure services. If no specific environment is recognized, it defaults to the Instance Metadata Service (IMDS).

    Detection logic based on environment variables:

    • SERVICE_FABRIC: Detected if IDENTITY_ENDPOINT and IDENTITY_HEADER are present, AND IDENTITY_SERVER_THUMBPRINT is present.
    • APP_SERVICE: Detected if IDENTITY_ENDPOINT and IDENTITY_HEADER are present, but IDENTITY_SERVER_THUMBPRINT is NOT present.
    • CLOUD_SHELL: Detected if MSI_ENDPOINT is present.
    • AZURE_ARC: Detected if IDENTITY_ENDPOINT and IMDS_ENDPOINT are present.
    • DEFAULT_TO_IMDS: Used if none of the above conditions are met.
  5. Configure PersistenceSettings for cross-platform support

    dev

    Use the PersistenceSettings.builder to define how the cache is stored and encrypted on different operating systems. You can specify the cache file name, the storage path, and platform-specific credentials for Keychain (macOS) or Keyring (Linux).

    private PersistenceSettings createPersistenceSettings() throws IOException {
        Path path = Paths.get(System.getProperty("user.home"), "MSAL", "testCache");
    
        return PersistenceSettings.builder("testCacheFile", path)
                .setMacKeychain("MsalTestService", "MsalTestAccount")
                .setLinuxKeyring(null,
                        "MsalTestSchema",
                        "MsalTestSecretLabel",
                        "MsalTestAttribute1Key",
                        "MsalTestAttribute1Value",
                        "MsalTestAttribute2Key",
                        "MsalTestAttribute2Value")
                .setLockRetry(1000, 50)
                .build();
    }
  6. Troubleshoot Linux browser opening failures in interactive flows

    dev

    When using interactive authentication flows on Linux, MSAL attempts to open the system browser using tools like xdg-open, gnome-open, kfmclient, or wslview. If these fail, you may encounter specific error codes.

    Common Linux Issues

    1. Missing Browser Tools: If MSAL cannot find any of the supported tools in your PATH, it will throw an exception with the error code linux_xdg_open_failed. Ensure that xdg-open or a similar tool is installed and accessible.
    2. Sudo Mode Restriction: MSAL cannot open a web page using browser tools when running in sudo mode. If you are running your process as a superuser, you will encounter the error: Unable to open a web page using xdg-open, gnome-open, kfmclient or wslview tools in sudo mode. Please run the process as non-sudo user.

    To resolve these, ensure you are running the application as a regular user and that the necessary desktop integration tools are installed.