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

interactive-user-authentication.mddocs/

0

# Interactive User Authentication

1

2

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.

3

4

## Interactive Browser Authentication

5

6

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

7

8

```java

9

import com.azure.identity.InteractiveBrowserCredential;

10

import com.azure.identity.InteractiveBrowserCredentialBuilder;

11

12

// Basic browser authentication

13

TokenCredential credential = new InteractiveBrowserCredentialBuilder()

14

.redirectUrl("http://localhost:8765") // Redirect URL for local development

15

.build();

16

17

// Use with Azure SDK client

18

GraphServiceClient graphClient = GraphServiceClient.builder()

19

.authenticationProvider(new TokenCredentialAuthProvider(credential))

20

.buildClient();

21

```

22

23

## Device Code Authentication

24

25

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

26

27

```java

28

import com.azure.identity.DeviceCodeCredential;

29

import com.azure.identity.DeviceCodeCredentialBuilder;

30

import com.azure.identity.DeviceCodeInfo;

31

32

// Device code with custom challenge handler

33

TokenCredential credential = new DeviceCodeCredentialBuilder()

34

.deviceCodeChallengeConsumer(deviceCodeInfo -> {

35

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

36

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

37

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

38

})

39

.build();

40

41

// Alternative: Default challenge handler prints to console

42

TokenCredential defaultCredential = new DeviceCodeCredentialBuilder().build();

43

```

44

45

## Username/Password Authentication

46

47

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

48

49

```java

50

import com.azure.identity.UsernamePasswordCredential;

51

import com.azure.identity.UsernamePasswordCredentialBuilder;

52

53

// Username/password authentication

54

TokenCredential credential = new UsernamePasswordCredentialBuilder()

55

.tenantId("tenant-id")

56

.clientId("client-id")

57

.username("user@domain.com")

58

.password("password")

59

.build();

60

```

61

62

## Authorization Code Authentication

63

64

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

65

66

```java

67

import com.azure.identity.AuthorizationCodeCredential;

68

import com.azure.identity.AuthorizationCodeCredentialBuilder;

69

70

// Use existing authorization code

71

TokenCredential credential = new AuthorizationCodeCredentialBuilder()

72

.tenantId("tenant-id")

73

.clientId("client-id")

74

.authorizationCode("authorization-code")

75

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

76

.build();

77

```

78

79

## Authentication Records

80

81

Store and reuse authentication state for seamless re-authentication.

82

83

```java

84

import com.azure.identity.AuthenticationRecord;

85

import java.io.FileInputStream;

86

import java.io.FileOutputStream;

87

88

// Initial authentication and record storage

89

InteractiveBrowserCredential credential = new InteractiveBrowserCredentialBuilder()

90

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

91

.build();

92

93

// Authenticate and get record

94

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

95

96

// Serialize to file

97

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

98

record.serialize(fos);

99

}

100

101

// Later: Deserialize and reuse

102

AuthenticationRecord savedRecord;

103

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

104

savedRecord = AuthenticationRecord.deserialize(fis);

105

}

106

107

// Create credential with saved authentication state

108

TokenCredential reusableCredential = new InteractiveBrowserCredentialBuilder()

109

.authenticationRecord(savedRecord)

110

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

111

.build();

112

```

113

114

## Browser Customization

115

116

Customize the browser authentication experience.

117

118

```java

119

import com.azure.identity.BrowserCustomizationOptions;

120

121

// Customize browser messages

122

BrowserCustomizationOptions customization = new BrowserCustomizationOptions()

123

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

124

.setErrorMessage("Authentication failed. Please try again.");

125

126

TokenCredential credential = new InteractiveBrowserCredentialBuilder()

127

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

128

.browserCustomizationOptions(customization)

129

.build();

130

```

131

132

## Multi-Tenant Configuration

133

134

```java

135

// Configure for multi-tenant scenarios

136

TokenCredential credential = new InteractiveBrowserCredentialBuilder()

137

.tenantId("primary-tenant-id")

138

.clientId("client-id")

139

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

140

.additionallyAllowedTenants("*") // Allow any tenant

141

.build();

142

```

143

144

## Advanced Configuration

145

146

```java

147

// Advanced configuration options

148

TokenCredential credential = new InteractiveBrowserCredentialBuilder()

149

.tenantId("tenant-id")

150

.clientId("client-id")

151

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

152

.authorityHost(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD)

153

.loginHint("user@domain.com") // Pre-fill username

154

.domainHint("domain.com") // Skip tenant discovery

155

.disableAutomaticAuthentication() // Require explicit authenticate() call

156

.executorService(executorService)

157

.httpClient(httpClient)

158

.build();

159

```

160

161

## Token Caching

162

163

Enable persistent token caching to avoid repeated authentication.

164

165

```java

166

import com.azure.identity.TokenCachePersistenceOptions;

167

168

// Configure persistent token cache

169

TokenCachePersistenceOptions cacheOptions = new TokenCachePersistenceOptions()

170

.setName("my-app-cache")

171

.setUnencryptedStorageAllowed(false); // Require encrypted storage

172

173

TokenCredential credential = new InteractiveBrowserCredentialBuilder()

174

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

175

.tokenCachePersistenceOptions(cacheOptions)

176

.build();

177

```

178

179

## Error Handling

180

181

```java

182

try {

183

InteractiveBrowserCredential credential = new InteractiveBrowserCredentialBuilder()

184

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

185

.build();

186

187

// Explicit authentication

188

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

189

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

190

191

// Get token

192

AccessToken token = credential.getTokenSync(

193

new TokenRequestContext().addScopes("https://graph.microsoft.com/.default")

194

);

195

196

} catch (AuthenticationRequiredException e) {

197

System.err.println("Interactive authentication required: " + e.getMessage());

198

// Handle case where automatic authentication is disabled

199

} catch (ClientAuthenticationException e) {

200

System.err.println("Authentication failed: " + e.getMessage());

201

// Handle authentication errors (user cancelled, invalid credentials, etc.)

202

}

203

```

204

205

## API Reference

206

207

```java { .api }

208

class InteractiveBrowserCredential implements TokenCredential {

209

Mono<AccessToken> getToken(TokenRequestContext request);

210

AccessToken getTokenSync(TokenRequestContext request);

211

Mono<AuthenticationRecord> authenticate(TokenRequestContext request);

212

Mono<AuthenticationRecord> authenticate();

213

}

214

215

class InteractiveBrowserCredentialBuilder extends AadCredentialBuilderBase<InteractiveBrowserCredentialBuilder> {

216

InteractiveBrowserCredentialBuilder redirectUrl(String redirectUrl);

217

InteractiveBrowserCredentialBuilder loginHint(String loginHint);

218

InteractiveBrowserCredentialBuilder domainHint(String domainHint);

219

InteractiveBrowserCredentialBuilder authenticationRecord(AuthenticationRecord authenticationRecord);

220

InteractiveBrowserCredentialBuilder disableAutomaticAuthentication();

221

InteractiveBrowserCredentialBuilder tokenCachePersistenceOptions(TokenCachePersistenceOptions tokenCachePersistenceOptions);

222

InteractiveBrowserCredentialBuilder browserCustomizationOptions(BrowserCustomizationOptions browserCustomizationOptions);

223

InteractiveBrowserCredential build();

224

}

225

226

class DeviceCodeCredential implements TokenCredential {

227

Mono<AccessToken> getToken(TokenRequestContext request);

228

AccessToken getTokenSync(TokenRequestContext request);

229

Mono<AuthenticationRecord> authenticate(TokenRequestContext request);

230

Mono<AuthenticationRecord> authenticate();

231

}

232

233

class DeviceCodeCredentialBuilder extends AadCredentialBuilderBase<DeviceCodeCredentialBuilder> {

234

DeviceCodeCredentialBuilder deviceCodeChallengeConsumer(Consumer<DeviceCodeInfo> challengeConsumer);

235

DeviceCodeCredentialBuilder maxRetry(int maxRetry);

236

DeviceCodeCredentialBuilder authenticationRecord(AuthenticationRecord authenticationRecord);

237

DeviceCodeCredentialBuilder disableAutomaticAuthentication();

238

DeviceCodeCredentialBuilder tokenCachePersistenceOptions(TokenCachePersistenceOptions tokenCachePersistenceOptions);

239

DeviceCodeCredential build();

240

}

241

242

class UsernamePasswordCredential implements TokenCredential {

243

Mono<AccessToken> getToken(TokenRequestContext request);

244

AccessToken getTokenSync(TokenRequestContext request);

245

Mono<AuthenticationRecord> authenticate(TokenRequestContext request);

246

Mono<AuthenticationRecord> authenticate();

247

}

248

249

class UsernamePasswordCredentialBuilder extends AadCredentialBuilderBase<UsernamePasswordCredentialBuilder> {

250

UsernamePasswordCredentialBuilder username(String username);

251

UsernamePasswordCredentialBuilder password(String password);

252

UsernamePasswordCredentialBuilder authenticationRecord(AuthenticationRecord authenticationRecord);

253

UsernamePasswordCredentialBuilder disableAutomaticAuthentication();

254

UsernamePasswordCredentialBuilder tokenCachePersistenceOptions(TokenCachePersistenceOptions tokenCachePersistenceOptions);

255

UsernamePasswordCredential build();

256

}

257

258

class AuthorizationCodeCredential implements TokenCredential {

259

Mono<AccessToken> getToken(TokenRequestContext request);

260

}

261

262

class AuthorizationCodeCredentialBuilder extends AadCredentialBuilderBase<AuthorizationCodeCredentialBuilder> {

263

AuthorizationCodeCredentialBuilder authorizationCode(String authorizationCode);

264

AuthorizationCodeCredentialBuilder redirectUrl(String redirectUrl);

265

AuthorizationCodeCredentialBuilder clientSecret(String clientSecret);

266

AuthorizationCodeCredential build();

267

}

268

269

class DeviceCodeInfo {

270

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

271

String getUserCode();

272

String getDeviceCode();

273

String getVerificationUrl();

274

OffsetDateTime getExpiresOn();

275

String getMessage();

276

}

277

278

class BrowserCustomizationOptions {

279

BrowserCustomizationOptions();

280

BrowserCustomizationOptions setSuccessMessage(String successMessage);

281

BrowserCustomizationOptions setErrorMessage(String errorMessage);

282

String getSuccessMessage();

283

String getErrorMessage();

284

}

285

```

286

287

## Best Practices

288

289

1. **Use Browser Authentication**: Prefer InteractiveBrowserCredential for desktop applications

290

2. **Device Code for Limited UI**: Use DeviceCodeCredential for command-line tools and IoT devices

291

3. **Avoid Username/Password**: Only use username/password authentication when other methods aren't available

292

4. **Store Authentication Records**: Save authentication records to avoid repeated user interaction

293

5. **Enable Token Caching**: Use persistent token caching for better user experience

294

6. **Handle Cancellation**: Gracefully handle cases where users cancel authentication

295

7. **Multi-Tenant Awareness**: Configure allowed tenants appropriately for your application

296

8. **Secure Redirect URLs**: Use HTTPS redirect URLs in production environments