docs
0
# Managed Identity Credential
1
2
ManagedIdentityCredential authenticates using Azure Managed Identity, providing a secure way for Azure-hosted applications to authenticate without storing credentials. It supports both system-assigned and user-assigned managed identities.
3
4
## System-Assigned Managed Identity
5
6
```java
7
import com.azure.identity.ManagedIdentityCredential;
8
import com.azure.identity.ManagedIdentityCredentialBuilder;
9
10
// Use system-assigned managed identity (default)
11
TokenCredential credential = new ManagedIdentityCredentialBuilder().build();
12
13
// Use with Azure SDK client
14
KeyVaultSecret secret = new SecretClientBuilder()
15
.vaultUrl("https://myvault.vault.azure.net/")
16
.credential(credential)
17
.buildClient()
18
.getSecret("my-secret");
19
```
20
21
## User-Assigned Managed Identity
22
23
```java
24
// Authenticate with user-assigned managed identity using client ID
25
TokenCredential credential = new ManagedIdentityCredentialBuilder()
26
.clientId("user-assigned-client-id")
27
.build();
28
29
// Alternative: use resource ID
30
TokenCredential credentialByResourceId = new ManagedIdentityCredentialBuilder()
31
.resourceId("/subscriptions/{subscription}/resourceGroups/{rg}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{name}")
32
.build();
33
```
34
35
## Supported Azure Services
36
37
ManagedIdentityCredential works in the following Azure environments:
38
39
- **Azure Virtual Machines**
40
- **Azure App Service**
41
- **Azure Functions**
42
- **Azure Container Instances**
43
- **Azure Kubernetes Service (AKS)**
44
- **Azure Service Fabric**
45
- **Azure Arc-enabled servers**
46
47
## Configuration Options
48
49
```java
50
// Configure with various options
51
TokenCredential credential = new ManagedIdentityCredentialBuilder()
52
.clientId("user-assigned-client-id") // For user-assigned identity
53
.maxRetry(3) // Maximum retry attempts
54
.retryTimeout(Duration.ofSeconds(30)) // Retry timeout
55
.httpClient(httpClient) // Custom HTTP client
56
.build();
57
```
58
59
## Error Handling
60
61
```java
62
try {
63
TokenCredential credential = new ManagedIdentityCredentialBuilder().build();
64
65
// Synchronous token acquisition
66
AccessToken token = credential.getTokenSync(
67
new TokenRequestContext().addScopes("https://vault.azure.net/.default")
68
);
69
70
System.out.println("Token expires at: " + token.getExpiresAt());
71
72
} catch (CredentialUnavailableException e) {
73
System.err.println("Managed Identity not available: " + e.getMessage());
74
// This typically means the code is not running in an Azure environment
75
// that supports Managed Identity
76
} catch (ClientAuthenticationException e) {
77
System.err.println("Authentication failed: " + e.getMessage());
78
}
79
```
80
81
## Async Usage
82
83
```java
84
import reactor.core.publisher.Mono;
85
86
TokenCredential credential = new ManagedIdentityCredentialBuilder().build();
87
88
// Asynchronous token acquisition
89
Mono<AccessToken> tokenMono = credential.getToken(
90
new TokenRequestContext().addScopes("https://management.azure.com/.default")
91
);
92
93
tokenMono.subscribe(
94
token -> System.out.println("Got token: " + token.getToken().substring(0, 10) + "..."),
95
error -> System.err.println("Failed to get token: " + error.getMessage())
96
);
97
```
98
99
## Environment Detection
100
101
ManagedIdentityCredential automatically detects the Azure environment and uses the appropriate endpoint:
102
103
- **Azure Virtual Machines**: Uses Azure Instance Metadata Service (IMDS)
104
- **App Service/Functions**: Uses MSI_ENDPOINT and MSI_SECRET environment variables
105
- **Service Fabric**: Uses IDENTITY_ENDPOINT and IDENTITY_HEADER environment variables
106
- **Azure Arc**: Uses IMDS with additional headers
107
108
## Getting Client ID
109
110
```java
111
ManagedIdentityCredential credential = new ManagedIdentityCredentialBuilder()
112
.clientId("user-assigned-client-id")
113
.build();
114
115
// Get the configured client ID
116
String clientId = credential.getClientId();
117
System.out.println("Using client ID: " + clientId);
118
```
119
120
## API Reference
121
122
```java { .api }
123
class ManagedIdentityCredential implements TokenCredential {
124
// Token acquisition
125
Mono<AccessToken> getToken(TokenRequestContext request);
126
AccessToken getTokenSync(TokenRequestContext request);
127
128
// Get the client ID of the managed identity
129
String getClientId();
130
}
131
132
class ManagedIdentityCredentialBuilder extends CredentialBuilderBase<ManagedIdentityCredentialBuilder> {
133
// Identity configuration
134
ManagedIdentityCredentialBuilder clientId(String clientId);
135
ManagedIdentityCredentialBuilder resourceId(String resourceId);
136
137
// Build method
138
ManagedIdentityCredential build();
139
}
140
```
141
142
## Best Practices
143
144
1. **Prefer System-Assigned**: Use system-assigned managed identity when possible for simplicity
145
2. **User-Assigned for Flexibility**: Use user-assigned managed identity when you need to share identity across resources
146
3. **Environment Validation**: Check that your code is running in a supported Azure environment
147
4. **Resource Permissions**: Ensure the managed identity has appropriate permissions for target resources
148
5. **Error Handling**: Always handle CredentialUnavailableException for non-Azure environments
149
6. **Token Caching**: The credential automatically handles token caching and refresh
150
151
## Troubleshooting
152
153
Common issues and solutions:
154
155
- **CredentialUnavailableException**: Code is not running in a supported Azure environment
156
- **403 Forbidden**: Managed identity doesn't have permission for the requested resource
157
- **Resource Not Found**: User-assigned managed identity client ID or resource ID is incorrect
158
- **Connection Timeout**: Network connectivity issues to the managed identity endpoint