or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

advanced-authentication-flows.mdauthorization-code-authentication.mdazure-developer-cli-authentication.mdazure-pipelines-authentication.mdclient-assertion-authentication.mdconfiguration-and-utilities.mdcredential-chaining.mddefault-azure-credential.mddeveloper-tool-credentials.mdenvironment-credential.mdindex.mdinteractive-user-authentication.mdmanaged-identity-credential.mdservice-principal-authentication.mdshared-token-cache-authentication.mdusername-password-authentication.mdvisual-studio-code-authentication.md

configuration-and-utilities.mddocs/

0

# Configuration and Utilities

1

2

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

3

4

## Azure Authority Hosts

5

6

Predefined authority hosts for different Azure cloud environments.

7

8

```java

9

import com.azure.identity.AzureAuthorityHosts;

10

11

// Use predefined authority hosts

12

TokenCredential publicCloudCredential = new ClientSecretCredentialBuilder()

13

.tenantId("tenant-id")

14

.clientId("client-id")

15

.clientSecret("client-secret")

16

.authorityHost(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD) // Default

17

.build();

18

19

TokenCredential govCloudCredential = new ClientSecretCredentialBuilder()

20

.tenantId("tenant-id")

21

.clientId("client-id")

22

.clientSecret("client-secret")

23

.authorityHost(AzureAuthorityHosts.AZURE_GOVERNMENT)

24

.build();

25

26

TokenCredential chinaCloudCredential = new ClientSecretCredentialBuilder()

27

.tenantId("tenant-id")

28

.clientId("client-id")

29

.clientSecret("client-secret")

30

.authorityHost(AzureAuthorityHosts.AZURE_CHINA)

31

.build();

32

```

33

34

## Authentication Records

35

36

Store and manage authentication state for seamless re-authentication.

37

38

```java

39

import com.azure.identity.AuthenticationRecord;

40

import java.io.*;

41

42

// Authenticate and get record

43

InteractiveBrowserCredential credential = new InteractiveBrowserCredentialBuilder()

44

.redirectUrl("http://localhost:8765")

45

.build();

46

47

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

48

49

// Access record information

50

System.out.println("Authority: " + record.getAuthority());

51

System.out.println("Tenant ID: " + record.getTenantId());

52

System.out.println("Client ID: " + record.getClientId());

53

System.out.println("Username: " + record.getUsername());

54

System.out.println("Home Account ID: " + record.getHomeAccountId());

55

56

// Serialize record to file

57

try (FileOutputStream fos = new FileOutputStream("auth-record.json")) {

58

record.serialize(fos);

59

}

60

61

// Deserialize record from file

62

AuthenticationRecord loadedRecord;

63

try (FileInputStream fis = new FileInputStream("auth-record.json")) {

64

loadedRecord = AuthenticationRecord.deserialize(fis);

65

}

66

67

// Use record with new credential instance

68

TokenCredential reusableCredential = new InteractiveBrowserCredentialBuilder()

69

.authenticationRecord(loadedRecord)

70

.redirectUrl("http://localhost:8765")

71

.build();

72

```

73

74

## Token Cache Persistence Options

75

76

Configure persistent token caching for improved user experience.

77

78

```java

79

import com.azure.identity.TokenCachePersistenceOptions;

80

81

// Configure token cache persistence

82

TokenCachePersistenceOptions cacheOptions = new TokenCachePersistenceOptions()

83

.setName("my-application-cache")

84

.setUnencryptedStorageAllowed(false); // Require encryption

85

86

TokenCredential credential = new InteractiveBrowserCredentialBuilder()

87

.redirectUrl("http://localhost:8765")

88

.tokenCachePersistenceOptions(cacheOptions)

89

.build();

90

91

// Check cache configuration

92

System.out.println("Cache name: " + cacheOptions.getName());

93

System.out.println("Unencrypted allowed: " + cacheOptions.isUnencryptedStorageAllowed());

94

```

95

96

## Device Code Information

97

98

Handle device code authentication flow information.

99

100

```java

101

import com.azure.identity.DeviceCodeInfo;

102

import java.time.OffsetDateTime;

103

104

// Custom device code challenge handler

105

TokenCredential deviceCredential = new DeviceCodeCredentialBuilder()

106

.deviceCodeChallengeConsumer(deviceCodeInfo -> {

107

System.out.println("=== Azure Device Code Authentication ===");

108

System.out.println("Open a web browser and navigate to: " + deviceCodeInfo.getVerificationUrl());

109

System.out.println("Enter the code: " + deviceCodeInfo.getUserCode());

110

System.out.println("Expires at: " + deviceCodeInfo.getExpiresOn());

111

System.out.println("Full message: " + deviceCodeInfo.getMessage());

112

System.out.println("========================================");

113

114

// Could also show a QR code, send a notification, etc.

115

})

116

.build();

117

```

118

119

## Browser Customization Options

120

121

Customize the browser authentication experience.

122

123

```java

124

import com.azure.identity.BrowserCustomizationOptions;

125

126

// Customize browser messages

127

BrowserCustomizationOptions customization = new BrowserCustomizationOptions()

128

.setSuccessMessage("✅ Authentication successful! You can safely close this browser window.")

129

.setErrorMessage("❌ Authentication failed. Please try again or contact support.");

130

131

TokenCredential credential = new InteractiveBrowserCredentialBuilder()

132

.redirectUrl("http://localhost:8765")

133

.browserCustomizationOptions(customization)

134

.build();

135

136

// Access customization settings

137

System.out.println("Success message: " + customization.getSuccessMessage());

138

System.out.println("Error message: " + customization.getErrorMessage());

139

```

140

141

## Authentication Utilities

142

143

Utility functions for common authentication tasks.

144

145

```java

146

import com.azure.identity.AuthenticationUtil;

147

import java.util.function.Supplier;

148

149

// Create bearer token supplier for HTTP clients

150

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

151

152

Supplier<String> tokenSupplier = AuthenticationUtil.getBearerTokenSupplier(

153

credential,

154

"https://management.azure.com/.default"

155

);

156

157

// Use with HTTP client

158

String bearerToken = tokenSupplier.get();

159

System.out.println("Bearer token: " + bearerToken.substring(0, 20) + "...");

160

161

// Refresh token automatically

162

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

163

```

164

165

## HTTP Client Configuration

166

167

Configure HTTP clients and pipeline policies for credentials.

168

169

```java

170

import com.azure.core.http.HttpClient;

171

import com.azure.core.http.HttpPipeline;

172

import com.azure.core.http.HttpPipelineBuilder;

173

import com.azure.core.http.policy.HttpLogOptions;

174

import com.azure.core.http.policy.HttpLogDetailLevel;

175

import com.azure.core.http.policy.RetryPolicy;

176

import com.azure.core.http.policy.RetryOptions;

177

178

// Configure custom HTTP client

179

HttpClient httpClient = HttpClient.createDefault();

180

181

// Configure HTTP logging

182

HttpLogOptions logOptions = new HttpLogOptions()

183

.setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)

184

.setAllowedHeaderNames(Set.of("x-ms-client-request-id"))

185

.setAllowedQueryParamNames(Set.of("api-version"));

186

187

// Configure retry policy

188

RetryOptions retryOptions = new RetryOptions(

189

ExponentialBackoff.builder()

190

.maxRetries(3)

191

.baseDelay(Duration.ofSeconds(1))

192

.maxDelay(Duration.ofSeconds(30))

193

.build()

194

);

195

196

// Apply to credential

197

TokenCredential credential = new ClientSecretCredentialBuilder()

198

.tenantId("tenant-id")

199

.clientId("client-id")

200

.clientSecret("client-secret")

201

.httpClient(httpClient)

202

.httpLogOptions(logOptions)

203

.retryOptions(retryOptions)

204

.build();

205

```

206

207

## Executor Service Configuration

208

209

Configure custom executor services for asynchronous operations.

210

211

```java

212

import java.util.concurrent.ExecutorService;

213

import java.util.concurrent.Executors;

214

215

// Create custom executor service

216

ExecutorService executorService = Executors.newFixedThreadPool(4);

217

218

// Configure credential with custom executor

219

TokenCredential credential = new InteractiveBrowserCredentialBuilder()

220

.redirectUrl("http://localhost:8765")

221

.executorService(executorService)

222

.build();

223

224

// Remember to shutdown executor when done

225

Runtime.getRuntime().addShutdownHook(new Thread(executorService::shutdown));

226

```

227

228

## Client Options Configuration

229

230

Configure client options for advanced scenarios.

231

232

```java

233

import com.azure.core.util.ClientOptions;

234

import com.azure.core.util.Header;

235

236

// Configure client options

237

ClientOptions clientOptions = new ClientOptions()

238

.setApplicationId("my-application")

239

.setHeaders(Arrays.asList(

240

new Header("Custom-Header", "custom-value"),

241

new Header("User-Agent", "MyApp/1.0")

242

));

243

244

TokenCredential credential = new DefaultAzureCredentialBuilder()

245

.clientOptions(clientOptions)

246

.build();

247

```

248

249

## Environment Variable Utilities

250

251

Helper methods for environment variable configuration.

252

253

```java

254

// Utility class for environment configuration

255

public class CredentialEnvironment {

256

257

public static boolean isConfiguredForServicePrincipal() {

258

return System.getenv("AZURE_CLIENT_ID") != null &&

259

System.getenv("AZURE_TENANT_ID") != null &&

260

(System.getenv("AZURE_CLIENT_SECRET") != null ||

261

System.getenv("AZURE_CLIENT_CERTIFICATE_PATH") != null);

262

}

263

264

public static boolean isConfiguredForManagedIdentity() {

265

return System.getenv("MSI_ENDPOINT") != null ||

266

System.getenv("IDENTITY_ENDPOINT") != null ||

267

isRunningInAzure();

268

}

269

270

public static boolean isRunningInAzure() {

271

// Check for Azure environment indicators

272

return System.getenv("WEBSITE_SITE_NAME") != null || // App Service

273

System.getenv("FUNCTIONS_WORKER_RUNTIME") != null || // Functions

274

System.getenv("CONTAINER_REGISTRY_LOGIN_SERVER") != null; // Container Instances

275

}

276

277

public static TokenCredential createOptimalCredential() {

278

if (isConfiguredForManagedIdentity()) {

279

return new ManagedIdentityCredentialBuilder().build();

280

} else if (isConfiguredForServicePrincipal()) {

281

return new EnvironmentCredentialBuilder().build();

282

} else {

283

return new DefaultAzureCredentialBuilder().build();

284

}

285

}

286

}

287

```

288

289

## Logging Configuration

290

291

Configure logging for authentication operations.

292

293

```java

294

import java.util.logging.Logger;

295

import java.util.logging.Level;

296

297

// Enable identity logging

298

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

299

300

// Or configure programmatically

301

Logger identityLogger = Logger.getLogger("com.azure.identity");

302

identityLogger.setLevel(Level.FINE);

303

304

// Enable account identifier logging for troubleshooting

305

TokenCredential credential = new DefaultAzureCredentialBuilder()

306

.enableAccountIdentifierLogging()

307

.build();

308

```

309

310

## API Reference

311

312

```java { .api }

313

class AzureAuthorityHosts {

314

static final String AZURE_PUBLIC_CLOUD = "https://login.microsoftonline.com/";

315

static final String AZURE_CHINA = "https://login.chinacloudapi.cn/";

316

static final String AZURE_GERMANY = "https://login.microsoftonline.de/"; // Deprecated

317

static final String AZURE_GOVERNMENT = "https://login.microsoftonline.us/";

318

}

319

320

class AuthenticationRecord {

321

// Getters

322

String getAuthority();

323

String getHomeAccountId();

324

String getTenantId();

325

String getClientId();

326

String getUsername();

327

328

// Serialization

329

Mono<OutputStream> serializeAsync(OutputStream outputStream);

330

void serialize(OutputStream outputStream);

331

static Mono<AuthenticationRecord> deserializeAsync(InputStream inputStream);

332

static AuthenticationRecord deserialize(InputStream inputStream);

333

}

334

335

class TokenCachePersistenceOptions {

336

TokenCachePersistenceOptions();

337

TokenCachePersistenceOptions setUnencryptedStorageAllowed(boolean unencryptedStorageAllowed);

338

boolean isUnencryptedStorageAllowed();

339

TokenCachePersistenceOptions setName(String name);

340

String getName();

341

}

342

343

class BrowserCustomizationOptions {

344

BrowserCustomizationOptions();

345

BrowserCustomizationOptions setSuccessMessage(String successMessage);

346

BrowserCustomizationOptions setErrorMessage(String errorMessage);

347

String getSuccessMessage();

348

String getErrorMessage();

349

}

350

351

class DeviceCodeInfo {

352

DeviceCodeInfo(String userCode, String deviceCode, String verificationUrl, OffsetDateTime expiresOn, String message);

353

String getUserCode();

354

String getDeviceCode();

355

String getVerificationUrl();

356

OffsetDateTime getExpiresOn();

357

String getMessage();

358

}

359

360

class AuthenticationUtil {

361

static Supplier<String> getBearerTokenSupplier(TokenCredential credential, String... scopes);

362

}

363

```

364

365

## Best Practices

366

367

1. **Use Appropriate Cloud**: Select the correct authority host for your target Azure cloud

368

2. **Persist Authentication Records**: Save authentication records to improve user experience

369

3. **Configure Token Caching**: Enable persistent token caching for better performance

370

4. **Customize User Experience**: Use browser customization options for better UX

371

5. **Environment Detection**: Use environment detection utilities to select optimal credentials

372

6. **Proper Logging**: Configure appropriate logging levels for troubleshooting

373

7. **Resource Management**: Properly dispose of custom executor services and HTTP clients

374

8. **Security**: Require encrypted token storage in production environments

375

376

## Troubleshooting

377

378

Common configuration issues and solutions:

379

380

- **Wrong Authority Host**: Verify you're using the correct authority for your Azure cloud

381

- **Cache Issues**: Clear token cache if authentication state becomes corrupted

382

- **Network Configuration**: Configure proxy settings and retry policies for network issues

383

- **Logging Problems**: Enable debug logging to troubleshoot authentication failures

384

- **Environment Variables**: Verify all required environment variables are properly set