The Azure Identity library provides Microsoft Entra ID token authentication support across the Azure SDK with a comprehensive set of TokenCredential implementations.
—
Azure Identity provides configuration classes, utility functions, and helper types to customize authentication behavior, manage authentication state, and integrate with Azure services.
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();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();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());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();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());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 expiredConfigure 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();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));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();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();
}
}
}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();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);
}Common configuration issues and solutions:
Install with Tessl CLI
npx tessl i tessl/maven-com-azure--azure-identitydocs