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

interactive-user-authentication.mddocs/

Interactive User Authentication

Interactive user authentication enables applications to authenticate users through various interactive flows. Azure Identity supports browser-based authentication, device code flow, and username/password authentication for scenarios requiring user interaction.

Interactive Browser Authentication

Opens a web browser for user authentication with Microsoft Entra ID.

import com.azure.identity.InteractiveBrowserCredential;
import com.azure.identity.InteractiveBrowserCredentialBuilder;

// Basic browser authentication
TokenCredential credential = new InteractiveBrowserCredentialBuilder()
    .redirectUrl("http://localhost:8765")  // Redirect URL for local development
    .build();

// Use with Azure SDK client
GraphServiceClient graphClient = GraphServiceClient.builder()
    .authenticationProvider(new TokenCredentialAuthProvider(credential))
    .buildClient();

Device Code Authentication

Perfect for devices with limited UI capabilities, such as IoT devices or command-line applications.

import com.azure.identity.DeviceCodeCredential;
import com.azure.identity.DeviceCodeCredentialBuilder;
import com.azure.identity.DeviceCodeInfo;

// Device code with custom challenge handler
TokenCredential credential = new DeviceCodeCredentialBuilder()
    .deviceCodeChallengeConsumer(deviceCodeInfo -> {
        System.out.println("Open browser and navigate to: " + deviceCodeInfo.getVerificationUrl());
        System.out.println("Enter the code: " + deviceCodeInfo.getUserCode());
        System.out.println("Message: " + deviceCodeInfo.getMessage());
    })
    .build();

// Alternative: Default challenge handler prints to console
TokenCredential defaultCredential = new DeviceCodeCredentialBuilder().build();

Username/Password Authentication

Direct username and password authentication (not recommended for production).

import com.azure.identity.UsernamePasswordCredential;
import com.azure.identity.UsernamePasswordCredentialBuilder;

// Username/password authentication
TokenCredential credential = new UsernamePasswordCredentialBuilder()
    .tenantId("tenant-id")
    .clientId("client-id")
    .username("user@domain.com")
    .password("password")
    .build();

Authorization Code Authentication

For applications that already have an authorization code from OAuth2 flow.

import com.azure.identity.AuthorizationCodeCredential;
import com.azure.identity.AuthorizationCodeCredentialBuilder;

// Use existing authorization code
TokenCredential credential = new AuthorizationCodeCredentialBuilder()
    .tenantId("tenant-id")
    .clientId("client-id")
    .authorizationCode("authorization-code")
    .redirectUrl("http://localhost:8765")
    .build();

Authentication Records

Store and reuse authentication state for seamless re-authentication.

import com.azure.identity.AuthenticationRecord;
import java.io.FileInputStream;
import java.io.FileOutputStream;

// Initial authentication and record storage
InteractiveBrowserCredential credential = new InteractiveBrowserCredentialBuilder()
    .redirectUrl("http://localhost:8765")
    .build();

// Authenticate and get record
AuthenticationRecord record = credential.authenticate().block();

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

// Later: Deserialize and reuse
AuthenticationRecord savedRecord;
try (FileInputStream fis = new FileInputStream("auth-record.json")) {
    savedRecord = AuthenticationRecord.deserialize(fis);
}

// Create credential with saved authentication state
TokenCredential reusableCredential = new InteractiveBrowserCredentialBuilder()
    .authenticationRecord(savedRecord)
    .redirectUrl("http://localhost:8765")
    .build();

Browser Customization

Customize the browser authentication experience.

import com.azure.identity.BrowserCustomizationOptions;

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

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

Multi-Tenant Configuration

// Configure for multi-tenant scenarios
TokenCredential credential = new InteractiveBrowserCredentialBuilder()
    .tenantId("primary-tenant-id")
    .clientId("client-id")
    .redirectUrl("http://localhost:8765")
    .additionallyAllowedTenants("*")  // Allow any tenant
    .build();

Advanced Configuration

// Advanced configuration options
TokenCredential credential = new InteractiveBrowserCredentialBuilder()
    .tenantId("tenant-id")
    .clientId("client-id")
    .redirectUrl("http://localhost:8765")
    .authorityHost(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD)
    .loginHint("user@domain.com")  // Pre-fill username
    .domainHint("domain.com")  // Skip tenant discovery
    .disableAutomaticAuthentication()  // Require explicit authenticate() call
    .executorService(executorService)
    .httpClient(httpClient)
    .build();

Token Caching

Enable persistent token caching to avoid repeated authentication.

import com.azure.identity.TokenCachePersistenceOptions;

// Configure persistent token cache
TokenCachePersistenceOptions cacheOptions = new TokenCachePersistenceOptions()
    .setName("my-app-cache")
    .setUnencryptedStorageAllowed(false);  // Require encrypted storage

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

Error Handling

try {
    InteractiveBrowserCredential credential = new InteractiveBrowserCredentialBuilder()
        .redirectUrl("http://localhost:8765")
        .build();
    
    // Explicit authentication
    AuthenticationRecord record = credential.authenticate().block();
    System.out.println("Authenticated user: " + record.getUsername());
    
    // Get token
    AccessToken token = credential.getTokenSync(
        new TokenRequestContext().addScopes("https://graph.microsoft.com/.default")
    );
    
} catch (AuthenticationRequiredException e) {
    System.err.println("Interactive authentication required: " + e.getMessage());
    // Handle case where automatic authentication is disabled
} catch (ClientAuthenticationException e) {
    System.err.println("Authentication failed: " + e.getMessage());
    // Handle authentication errors (user cancelled, invalid credentials, etc.)
}

API Reference

class InteractiveBrowserCredential implements TokenCredential {
    Mono<AccessToken> getToken(TokenRequestContext request);
    AccessToken getTokenSync(TokenRequestContext request);
    Mono<AuthenticationRecord> authenticate(TokenRequestContext request);
    Mono<AuthenticationRecord> authenticate();
}

class InteractiveBrowserCredentialBuilder extends AadCredentialBuilderBase<InteractiveBrowserCredentialBuilder> {
    InteractiveBrowserCredentialBuilder redirectUrl(String redirectUrl);
    InteractiveBrowserCredentialBuilder loginHint(String loginHint);
    InteractiveBrowserCredentialBuilder domainHint(String domainHint);
    InteractiveBrowserCredentialBuilder authenticationRecord(AuthenticationRecord authenticationRecord);
    InteractiveBrowserCredentialBuilder disableAutomaticAuthentication();
    InteractiveBrowserCredentialBuilder tokenCachePersistenceOptions(TokenCachePersistenceOptions tokenCachePersistenceOptions);
    InteractiveBrowserCredentialBuilder browserCustomizationOptions(BrowserCustomizationOptions browserCustomizationOptions);
    InteractiveBrowserCredential build();
}

class DeviceCodeCredential implements TokenCredential {
    Mono<AccessToken> getToken(TokenRequestContext request);
    AccessToken getTokenSync(TokenRequestContext request);
    Mono<AuthenticationRecord> authenticate(TokenRequestContext request);
    Mono<AuthenticationRecord> authenticate();
}

class DeviceCodeCredentialBuilder extends AadCredentialBuilderBase<DeviceCodeCredentialBuilder> {
    DeviceCodeCredentialBuilder deviceCodeChallengeConsumer(Consumer<DeviceCodeInfo> challengeConsumer);
    DeviceCodeCredentialBuilder maxRetry(int maxRetry);
    DeviceCodeCredentialBuilder authenticationRecord(AuthenticationRecord authenticationRecord);
    DeviceCodeCredentialBuilder disableAutomaticAuthentication();
    DeviceCodeCredentialBuilder tokenCachePersistenceOptions(TokenCachePersistenceOptions tokenCachePersistenceOptions);
    DeviceCodeCredential build();
}

class UsernamePasswordCredential implements TokenCredential {
    Mono<AccessToken> getToken(TokenRequestContext request);
    AccessToken getTokenSync(TokenRequestContext request);
    Mono<AuthenticationRecord> authenticate(TokenRequestContext request);
    Mono<AuthenticationRecord> authenticate();
}

class UsernamePasswordCredentialBuilder extends AadCredentialBuilderBase<UsernamePasswordCredentialBuilder> {
    UsernamePasswordCredentialBuilder username(String username);
    UsernamePasswordCredentialBuilder password(String password);
    UsernamePasswordCredentialBuilder authenticationRecord(AuthenticationRecord authenticationRecord);
    UsernamePasswordCredentialBuilder disableAutomaticAuthentication();
    UsernamePasswordCredentialBuilder tokenCachePersistenceOptions(TokenCachePersistenceOptions tokenCachePersistenceOptions);
    UsernamePasswordCredential build();
}

class AuthorizationCodeCredential implements TokenCredential {
    Mono<AccessToken> getToken(TokenRequestContext request);
}

class AuthorizationCodeCredentialBuilder extends AadCredentialBuilderBase<AuthorizationCodeCredentialBuilder> {
    AuthorizationCodeCredentialBuilder authorizationCode(String authorizationCode);
    AuthorizationCodeCredentialBuilder redirectUrl(String redirectUrl);
    AuthorizationCodeCredentialBuilder clientSecret(String clientSecret);
    AuthorizationCodeCredential build();
}

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

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

Best Practices

  1. Use Browser Authentication: Prefer InteractiveBrowserCredential for desktop applications
  2. Device Code for Limited UI: Use DeviceCodeCredential for command-line tools and IoT devices
  3. Avoid Username/Password: Only use username/password authentication when other methods aren't available
  4. Store Authentication Records: Save authentication records to avoid repeated user interaction
  5. Enable Token Caching: Use persistent token caching for better user experience
  6. Handle Cancellation: Gracefully handle cases where users cancel authentication
  7. Multi-Tenant Awareness: Configure allowed tenants appropriately for your application
  8. Secure Redirect URLs: Use HTTPS redirect URLs in production environments

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