docs
0
# Service Principal Authentication
1
2
Service Principal authentication enables non-interactive authentication to Azure services using application credentials. Azure Identity supports three types of service principal authentication: client secret, client certificate, and client assertion.
3
4
## Client Secret Authentication
5
6
Authenticate using a service principal with a client secret.
7
8
```java
9
import com.azure.identity.ClientSecretCredential;
10
import com.azure.identity.ClientSecretCredentialBuilder;
11
12
// Basic client secret authentication
13
TokenCredential credential = new ClientSecretCredentialBuilder()
14
.tenantId("tenant-id")
15
.clientId("client-id")
16
.clientSecret("client-secret")
17
.build();
18
19
// Use with Azure SDK client
20
BlobServiceClient client = new BlobServiceClientBuilder()
21
.endpoint("https://mystorageaccount.blob.core.windows.net/")
22
.credential(credential)
23
.buildClient();
24
```
25
26
## Client Certificate Authentication
27
28
Authenticate using a service principal with a client certificate.
29
30
```java
31
import com.azure.identity.ClientCertificateCredential;
32
import com.azure.identity.ClientCertificateCredentialBuilder;
33
34
// From certificate file
35
TokenCredential credential = new ClientCertificateCredentialBuilder()
36
.tenantId("tenant-id")
37
.clientId("client-id")
38
.pfxCertificate("path/to/certificate.pfx", "certificate-password")
39
.build();
40
41
// From PEM certificate
42
TokenCredential pemCredential = new ClientCertificateCredentialBuilder()
43
.tenantId("tenant-id")
44
.clientId("client-id")
45
.pemCertificate("path/to/certificate.pem")
46
.build();
47
```
48
49
## Client Assertion Authentication
50
51
Authenticate using a signed client assertion.
52
53
```java
54
import com.azure.identity.ClientAssertionCredential;
55
import com.azure.identity.ClientAssertionCredentialBuilder;
56
import java.util.function.Supplier;
57
58
// Using assertion supplier
59
Supplier<String> assertionSupplier = () -> {
60
// Your logic to generate or retrieve the client assertion
61
return generateJwtAssertion();
62
};
63
64
TokenCredential credential = new ClientAssertionCredentialBuilder()
65
.tenantId("tenant-id")
66
.clientId("client-id")
67
.clientAssertion(assertionSupplier)
68
.build();
69
```
70
71
## Advanced Configuration
72
73
```java
74
// Configure with custom options
75
TokenCredential credential = new ClientSecretCredentialBuilder()
76
.tenantId("tenant-id")
77
.clientId("client-id")
78
.clientSecret("client-secret")
79
.authorityHost(AzureAuthorityHosts.AZURE_GOVERNMENT) // Government cloud
80
.additionallyAllowedTenants("*") // Allow any tenant
81
.disableInstanceDiscovery() // Disable instance discovery
82
.executorService(executorService) // Custom executor
83
.httpClient(httpClient) // Custom HTTP client
84
.build();
85
```
86
87
## Multi-Tenant Authentication
88
89
```java
90
// Configure for multi-tenant scenarios
91
TokenCredential credential = new ClientSecretCredentialBuilder()
92
.tenantId("primary-tenant-id")
93
.clientId("client-id")
94
.clientSecret("client-secret")
95
.additionallyAllowedTenants("tenant-1", "tenant-2", "tenant-3")
96
.build();
97
98
// Or allow any tenant
99
TokenCredential anyTenantCredential = new ClientSecretCredentialBuilder()
100
.tenantId("primary-tenant-id")
101
.clientId("client-id")
102
.clientSecret("client-secret")
103
.additionallyAllowedTenants("*")
104
.build();
105
```
106
107
## Environment Variables
108
109
Service principal credentials can be configured via environment variables:
110
111
- **AZURE_CLIENT_ID** - The client ID of the service principal
112
- **AZURE_CLIENT_SECRET** - The client secret
113
- **AZURE_CLIENT_CERTIFICATE_PATH** - Path to certificate file
114
- **AZURE_CLIENT_CERTIFICATE_PASSWORD** - Certificate password
115
- **AZURE_TENANT_ID** - The tenant ID
116
- **AZURE_AUTHORITY_HOST** - The Microsoft Entra ID authority host
117
118
```java
119
// EnvironmentCredential reads these automatically
120
import com.azure.identity.EnvironmentCredential;
121
import com.azure.identity.EnvironmentCredentialBuilder;
122
123
TokenCredential envCredential = new EnvironmentCredentialBuilder().build();
124
```
125
126
## Certificate Formats
127
128
### PFX/PKCS#12 Certificate
129
130
```java
131
// With password
132
TokenCredential credential = new ClientCertificateCredentialBuilder()
133
.tenantId("tenant-id")
134
.clientId("client-id")
135
.pfxCertificate("path/to/certificate.pfx", "password")
136
.build();
137
138
// Without password
139
TokenCredential credentialNoPassword = new ClientCertificateCredentialBuilder()
140
.tenantId("tenant-id")
141
.clientId("client-id")
142
.pfxCertificate("path/to/certificate.pfx")
143
.build();
144
```
145
146
### PEM Certificate
147
148
```java
149
// PEM certificate with private key
150
TokenCredential credential = new ClientCertificateCredentialBuilder()
151
.tenantId("tenant-id")
152
.clientId("client-id")
153
.pemCertificate("path/to/certificate.pem")
154
.build();
155
156
// Send certificate chain in token request
157
TokenCredential credentialWithChain = new ClientCertificateCredentialBuilder()
158
.tenantId("tenant-id")
159
.clientId("client-id")
160
.pemCertificate("path/to/certificate.pem")
161
.sendCertificateChain(true)
162
.build();
163
```
164
165
## Error Handling
166
167
```java
168
try {
169
TokenCredential credential = new ClientSecretCredentialBuilder()
170
.tenantId("tenant-id")
171
.clientId("client-id")
172
.clientSecret("client-secret")
173
.build();
174
175
AccessToken token = credential.getTokenSync(
176
new TokenRequestContext().addScopes("https://management.azure.com/.default")
177
);
178
179
System.out.println("Authentication successful");
180
181
} catch (ClientAuthenticationException e) {
182
System.err.println("Authentication failed: " + e.getMessage());
183
// Common causes:
184
// - Invalid client ID, secret, or tenant ID
185
// - Service principal doesn't exist or is disabled
186
// - Insufficient permissions for requested scope
187
} catch (Exception e) {
188
System.err.println("Unexpected error: " + e.getMessage());
189
}
190
```
191
192
## API Reference
193
194
```java { .api }
195
class ClientSecretCredential implements TokenCredential {
196
Mono<AccessToken> getToken(TokenRequestContext request);
197
AccessToken getTokenSync(TokenRequestContext request);
198
}
199
200
class ClientSecretCredentialBuilder extends AadCredentialBuilderBase<ClientSecretCredentialBuilder> {
201
ClientSecretCredentialBuilder clientSecret(String clientSecret);
202
ClientSecretCredential build();
203
}
204
205
class ClientCertificateCredential implements TokenCredential {
206
Mono<AccessToken> getToken(TokenRequestContext request);
207
AccessToken getTokenSync(TokenRequestContext request);
208
}
209
210
class ClientCertificateCredentialBuilder extends AadCredentialBuilderBase<ClientCertificateCredentialBuilder> {
211
ClientCertificateCredentialBuilder pfxCertificate(String certificatePath);
212
ClientCertificateCredentialBuilder pfxCertificate(String certificatePath, String clientCertificatePassword);
213
ClientCertificateCredentialBuilder pfxCertificate(InputStream certificate, String clientCertificatePassword);
214
ClientCertificateCredentialBuilder pemCertificate(String certificatePath);
215
ClientCertificateCredentialBuilder pemCertificate(InputStream certificate);
216
ClientCertificateCredentialBuilder sendCertificateChain(boolean sendCertificateChain);
217
ClientCertificateCredential build();
218
}
219
220
class ClientAssertionCredential implements TokenCredential {
221
Mono<AccessToken> getToken(TokenRequestContext request);
222
AccessToken getTokenSync(TokenRequestContext request);
223
}
224
225
class ClientAssertionCredentialBuilder extends AadCredentialBuilderBase<ClientAssertionCredentialBuilder> {
226
ClientAssertionCredentialBuilder clientAssertion(Supplier<String> clientAssertionSupplier);
227
ClientAssertionCredential build();
228
}
229
230
class EnvironmentCredential implements TokenCredential {
231
Mono<AccessToken> getToken(TokenRequestContext request);
232
AccessToken getTokenSync(TokenRequestContext request);
233
}
234
235
class EnvironmentCredentialBuilder extends CredentialBuilderBase<EnvironmentCredentialBuilder> {
236
EnvironmentCredential build();
237
}
238
```
239
240
## Best Practices
241
242
1. **Secure Secret Storage**: Never hardcode client secrets in source code. Use Azure Key Vault or environment variables
243
2. **Certificate Over Secret**: Prefer client certificates over client secrets for enhanced security
244
3. **Short-Lived Secrets**: Rotate client secrets regularly and use short expiration times
245
4. **Least Privilege**: Grant service principals only the minimum required permissions
246
5. **Multi-Tenant Configuration**: Explicitly configure allowed tenants to prevent unauthorized access
247
6. **Certificate Chain**: Include the full certificate chain when using intermediate certificates
248
7. **Error Handling**: Implement retry logic for transient authentication failures
249
8. **Token Caching**: All service principal credentials automatically cache and refresh tokens