CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-com-azure--azure-identity

The Azure Identity library provides Microsoft Entra ID token authentication support across the Azure SDK with a comprehensive set of TokenCredential implementations.

Pending
Overview
Eval results
Files

configuration-and-utilities.mddocs/

Configuration and Utilities

Azure Identity provides configuration classes, utility functions, and helper types to customize authentication behavior, manage authentication state, and integrate with Azure services.

Azure Authority Hosts

Predefined authority hosts for different Azure cloud environments.

import com.azure.identity.AzureAuthorityHosts;

// Use predefined authority hosts
TokenCredential publicCloudCredential = new ClientSecretCredentialBuilder()
    .tenantId("tenant-id")
    .clientId("client-id")
    .clientSecret("client-secret")
    .authorityHost(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD)  // Default
    .build();

TokenCredential govCloudCredential = new ClientSecretCredentialBuilder()
    .tenantId("tenant-id")
    .clientId("client-id")
    .clientSecret("client-secret")
    .authorityHost(AzureAuthorityHosts.AZURE_GOVERNMENT)
    .build();

TokenCredential chinaCloudCredential = new ClientSecretCredentialBuilder()
    .tenantId("tenant-id")
    .clientId("client-id")
    .clientSecret("client-secret")
    .authorityHost(AzureAuthorityHosts.AZURE_CHINA)
    .build();

Authentication Records

Store and manage authentication state for seamless re-authentication.

import com.azure.identity.AuthenticationRecord;
import java.io.*;

// Authenticate and get record
InteractiveBrowserCredential credential = new InteractiveBrowserCredentialBuilder()
    .redirectUrl("http://localhost:8765")
    .build();

AuthenticationRecord record = credential.authenticate().block();

// Access record information
System.out.println("Authority: " + record.getAuthority());
System.out.println("Tenant ID: " + record.getTenantId());
System.out.println("Client ID: " + record.getClientId());
System.out.println("Username: " + record.getUsername());
System.out.println("Home Account ID: " + record.getHomeAccountId());

// Serialize record to file
try (FileOutputStream fos = new FileOutputStream("auth-record.json")) {
    record.serialize(fos);
}

// Deserialize record from file
AuthenticationRecord loadedRecord;
try (FileInputStream fis = new FileInputStream("auth-record.json")) {
    loadedRecord = AuthenticationRecord.deserialize(fis);
}

// Use record with new credential instance
TokenCredential reusableCredential = new InteractiveBrowserCredentialBuilder()
    .authenticationRecord(loadedRecord)
    .redirectUrl("http://localhost:8765")
    .build();

Token Cache Persistence Options

Configure persistent token caching for improved user experience.

import com.azure.identity.TokenCachePersistenceOptions;

// Configure token cache persistence
TokenCachePersistenceOptions cacheOptions = new TokenCachePersistenceOptions()
    .setName("my-application-cache")
    .setUnencryptedStorageAllowed(false);  // Require encryption

TokenCredential credential = new InteractiveBrowserCredentialBuilder()
    .redirectUrl("http://localhost:8765")
    .tokenCachePersistenceOptions(cacheOptions)
    .build();

// Check cache configuration
System.out.println("Cache name: " + cacheOptions.getName());
System.out.println("Unencrypted allowed: " + cacheOptions.isUnencryptedStorageAllowed());

Device Code Information

Handle device code authentication flow information.

import com.azure.identity.DeviceCodeInfo;
import java.time.OffsetDateTime;

// Custom device code challenge handler
TokenCredential deviceCredential = new DeviceCodeCredentialBuilder()
    .deviceCodeChallengeConsumer(deviceCodeInfo -> {
        System.out.println("=== Azure Device Code Authentication ===");
        System.out.println("Open a web browser and navigate to: " + deviceCodeInfo.getVerificationUrl());
        System.out.println("Enter the code: " + deviceCodeInfo.getUserCode());
        System.out.println("Expires at: " + deviceCodeInfo.getExpiresOn());
        System.out.println("Full message: " + deviceCodeInfo.getMessage());
        System.out.println("========================================");
        
        // Could also show a QR code, send a notification, etc.
    })
    .build();

Browser Customization Options

Customize the browser authentication experience.

import com.azure.identity.BrowserCustomizationOptions;

// Customize browser messages
BrowserCustomizationOptions customization = new BrowserCustomizationOptions()
    .setSuccessMessage("✅ Authentication successful! You can safely close this browser window.")
    .setErrorMessage("❌ Authentication failed. Please try again or contact support.");

TokenCredential credential = new InteractiveBrowserCredentialBuilder()
    .redirectUrl("http://localhost:8765")
    .browserCustomizationOptions(customization)
    .build();

// Access customization settings
System.out.println("Success message: " + customization.getSuccessMessage());
System.out.println("Error message: " + customization.getErrorMessage());

Authentication Utilities

Utility functions for common authentication tasks.

import com.azure.identity.AuthenticationUtil;
import java.util.function.Supplier;

// Create bearer token supplier for HTTP clients
TokenCredential credential = new DefaultAzureCredentialBuilder().build();

Supplier<String> tokenSupplier = AuthenticationUtil.getBearerTokenSupplier(
    credential,
    "https://management.azure.com/.default"
);

// Use with HTTP client
String bearerToken = tokenSupplier.get();
System.out.println("Bearer token: " + bearerToken.substring(0, 20) + "...");

// Refresh token automatically
String refreshedToken = tokenSupplier.get();  // Gets new token if expired

HTTP Client Configuration

Configure HTTP clients and pipeline policies for credentials.

import com.azure.core.http.HttpClient;
import com.azure.core.http.HttpPipeline;
import com.azure.core.http.HttpPipelineBuilder;
import com.azure.core.http.policy.HttpLogOptions;
import com.azure.core.http.policy.HttpLogDetailLevel;
import com.azure.core.http.policy.RetryPolicy;
import com.azure.core.http.policy.RetryOptions;

// Configure custom HTTP client
HttpClient httpClient = HttpClient.createDefault();

// Configure HTTP logging
HttpLogOptions logOptions = new HttpLogOptions()
    .setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)
    .setAllowedHeaderNames(Set.of("x-ms-client-request-id"))
    .setAllowedQueryParamNames(Set.of("api-version"));

// Configure retry policy
RetryOptions retryOptions = new RetryOptions(
    ExponentialBackoff.builder()
        .maxRetries(3)
        .baseDelay(Duration.ofSeconds(1))
        .maxDelay(Duration.ofSeconds(30))
        .build()
);

// Apply to credential
TokenCredential credential = new ClientSecretCredentialBuilder()
    .tenantId("tenant-id")
    .clientId("client-id")
    .clientSecret("client-secret")
    .httpClient(httpClient)
    .httpLogOptions(logOptions)
    .retryOptions(retryOptions)
    .build();

Executor Service Configuration

Configure custom executor services for asynchronous operations.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

// Create custom executor service
ExecutorService executorService = Executors.newFixedThreadPool(4);

// Configure credential with custom executor
TokenCredential credential = new InteractiveBrowserCredentialBuilder()
    .redirectUrl("http://localhost:8765")
    .executorService(executorService)
    .build();

// Remember to shutdown executor when done
Runtime.getRuntime().addShutdownHook(new Thread(executorService::shutdown));

Client Options Configuration

Configure client options for advanced scenarios.

import com.azure.core.util.ClientOptions;
import com.azure.core.util.Header;

// Configure client options
ClientOptions clientOptions = new ClientOptions()
    .setApplicationId("my-application")
    .setHeaders(Arrays.asList(
        new Header("Custom-Header", "custom-value"),
        new Header("User-Agent", "MyApp/1.0")
    ));

TokenCredential credential = new DefaultAzureCredentialBuilder()
    .clientOptions(clientOptions)
    .build();

Environment Variable Utilities

Helper methods for environment variable configuration.

// Utility class for environment configuration
public class CredentialEnvironment {
    
    public static boolean isConfiguredForServicePrincipal() {
        return System.getenv("AZURE_CLIENT_ID") != null &&
               System.getenv("AZURE_TENANT_ID") != null &&
               (System.getenv("AZURE_CLIENT_SECRET") != null ||
                System.getenv("AZURE_CLIENT_CERTIFICATE_PATH") != null);
    }
    
    public static boolean isConfiguredForManagedIdentity() {
        return System.getenv("MSI_ENDPOINT") != null ||
               System.getenv("IDENTITY_ENDPOINT") != null ||
               isRunningInAzure();
    }
    
    public static boolean isRunningInAzure() {
        // Check for Azure environment indicators
        return System.getenv("WEBSITE_SITE_NAME") != null ||  // App Service
               System.getenv("FUNCTIONS_WORKER_RUNTIME") != null ||  // Functions
               System.getenv("CONTAINER_REGISTRY_LOGIN_SERVER") != null;  // Container Instances
    }
    
    public static TokenCredential createOptimalCredential() {
        if (isConfiguredForManagedIdentity()) {
            return new ManagedIdentityCredentialBuilder().build();
        } else if (isConfiguredForServicePrincipal()) {
            return new EnvironmentCredentialBuilder().build();
        } else {
            return new DefaultAzureCredentialBuilder().build();
        }
    }
}

Logging Configuration

Configure logging for authentication operations.

import java.util.logging.Logger;
import java.util.logging.Level;

// Enable identity logging
System.setProperty("com.azure.identity", "DEBUG");

// Or configure programmatically
Logger identityLogger = Logger.getLogger("com.azure.identity");
identityLogger.setLevel(Level.FINE);

// Enable account identifier logging for troubleshooting
TokenCredential credential = new DefaultAzureCredentialBuilder()
    .enableAccountIdentifierLogging()
    .build();

API Reference

class AzureAuthorityHosts {
    static final String AZURE_PUBLIC_CLOUD = "https://login.microsoftonline.com/";
    static final String AZURE_CHINA = "https://login.chinacloudapi.cn/";
    static final String AZURE_GERMANY = "https://login.microsoftonline.de/";  // Deprecated
    static final String AZURE_GOVERNMENT = "https://login.microsoftonline.us/";
}

class AuthenticationRecord {
    // Getters
    String getAuthority();
    String getHomeAccountId();
    String getTenantId();
    String getClientId();
    String getUsername();
    
    // Serialization
    Mono<OutputStream> serializeAsync(OutputStream outputStream);
    void serialize(OutputStream outputStream);
    static Mono<AuthenticationRecord> deserializeAsync(InputStream inputStream);
    static AuthenticationRecord deserialize(InputStream inputStream);
}

class TokenCachePersistenceOptions {
    TokenCachePersistenceOptions();
    TokenCachePersistenceOptions setUnencryptedStorageAllowed(boolean unencryptedStorageAllowed);
    boolean isUnencryptedStorageAllowed();
    TokenCachePersistenceOptions setName(String name);
    String getName();
}

class BrowserCustomizationOptions {
    BrowserCustomizationOptions();
    BrowserCustomizationOptions setSuccessMessage(String successMessage);
    BrowserCustomizationOptions setErrorMessage(String errorMessage);
    String getSuccessMessage();
    String getErrorMessage();
}

class DeviceCodeInfo {
    DeviceCodeInfo(String userCode, String deviceCode, String verificationUrl, OffsetDateTime expiresOn, String message);
    String getUserCode();
    String getDeviceCode();
    String getVerificationUrl();
    OffsetDateTime getExpiresOn();
    String getMessage();
}

class AuthenticationUtil {
    static Supplier<String> getBearerTokenSupplier(TokenCredential credential, String... scopes);
}

Best Practices

  1. Use Appropriate Cloud: Select the correct authority host for your target Azure cloud
  2. Persist Authentication Records: Save authentication records to improve user experience
  3. Configure Token Caching: Enable persistent token caching for better performance
  4. Customize User Experience: Use browser customization options for better UX
  5. Environment Detection: Use environment detection utilities to select optimal credentials
  6. Proper Logging: Configure appropriate logging levels for troubleshooting
  7. Resource Management: Properly dispose of custom executor services and HTTP clients
  8. Security: Require encrypted token storage in production environments

Troubleshooting

Common configuration issues and solutions:

  • Wrong Authority Host: Verify you're using the correct authority for your Azure cloud
  • Cache Issues: Clear token cache if authentication state becomes corrupted
  • Network Configuration: Configure proxy settings and retry policies for network issues
  • Logging Problems: Enable debug logging to troubleshoot authentication failures
  • Environment Variables: Verify all required environment variables are properly set

Install with Tessl CLI

npx tessl i tessl/maven-com-azure--azure-identity

docs

advanced-authentication-flows.md

authorization-code-authentication.md

azure-developer-cli-authentication.md

azure-pipelines-authentication.md

client-assertion-authentication.md

configuration-and-utilities.md

credential-chaining.md

default-azure-credential.md

developer-tool-credentials.md

environment-credential.md

index.md

interactive-user-authentication.md

managed-identity-credential.md

service-principal-authentication.md

shared-token-cache-authentication.md

username-password-authentication.md

visual-studio-code-authentication.md

tile.json