0
# Authentication and Security
1
2
Apache HttpClient provides comprehensive authentication mechanisms including Basic, Digest, NTLM, and Kerberos authentication schemes, along with credential management and SSL/TLS support for secure communications.
3
4
## Credentials and Authentication Scope
5
6
### Credentials Interface
7
8
```java { .api }
9
public interface Credentials {
10
Principal getUserPrincipal();
11
String getPassword();
12
}
13
```
14
15
Base interface for authentication credentials.
16
17
### UsernamePasswordCredentials
18
19
```java { .api }
20
public class UsernamePasswordCredentials implements Credentials {
21
public UsernamePasswordCredentials(String userName, String password);
22
public Principal getUserPrincipal();
23
public String getPassword();
24
public String getUserName();
25
}
26
```
27
28
Basic username/password credentials implementation.
29
30
```java
31
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("username", "password");
32
```
33
34
### NTCredentials
35
36
```java { .api }
37
public class NTCredentials implements Credentials {
38
public NTCredentials(String userName, String password, String workstation, String domain);
39
public Principal getUserPrincipal();
40
public String getPassword();
41
public String getUserName();
42
public String getDomain();
43
public String getWorkstation();
44
}
45
```
46
47
Windows NT domain credentials for NTLM authentication.
48
49
```java
50
NTCredentials ntCredentials = new NTCredentials("username", "password", "workstation", "domain");
51
```
52
53
### KerberosCredentials
54
55
```java { .api }
56
public class KerberosCredentials implements Credentials {
57
public KerberosCredentials(GSSCredential gssCredential);
58
public Principal getUserPrincipal();
59
public String getPassword();
60
public GSSCredential getGSSCredential();
61
}
62
```
63
64
Kerberos credentials for Kerberos authentication.
65
66
### AuthScope
67
68
```java { .api }
69
public class AuthScope {
70
public static final AuthScope ANY;
71
public static final String ANY_HOST;
72
public static final int ANY_PORT;
73
public static final String ANY_REALM;
74
public static final String ANY_SCHEME;
75
76
public AuthScope(String host, int port);
77
public AuthScope(HttpHost host);
78
public AuthScope(String host, int port, String realm);
79
public AuthScope(String host, int port, String realm, String scheme);
80
public String getHost();
81
public int getPort();
82
public String getRealm();
83
public String getScheme();
84
public int match(AuthScope that);
85
}
86
```
87
88
Defines the scope (host, port, realm, scheme) for which credentials are valid.
89
90
```java
91
AuthScope authScope = new AuthScope("api.example.com", 443, "Protected Area", "basic");
92
```
93
94
## Credentials Provider
95
96
### CredentialsProvider Interface
97
98
```java { .api }
99
public interface CredentialsProvider {
100
void setCredentials(AuthScope authscope, Credentials credentials);
101
Credentials getCredentials(AuthScope authscope);
102
void clear();
103
}
104
```
105
106
Provider interface for managing authentication credentials.
107
108
### BasicCredentialsProvider
109
110
```java { .api }
111
public class BasicCredentialsProvider implements CredentialsProvider {
112
public BasicCredentialsProvider();
113
public void setCredentials(AuthScope authscope, Credentials credentials);
114
public Credentials getCredentials(AuthScope authscope);
115
public void clear();
116
}
117
```
118
119
Basic implementation of credentials provider.
120
121
```java
122
CredentialsProvider credsProvider = new BasicCredentialsProvider();
123
credsProvider.setCredentials(
124
new AuthScope("api.example.com", 80),
125
new UsernamePasswordCredentials("user", "password")
126
);
127
128
CloseableHttpClient httpClient = HttpClients.custom()
129
.setDefaultCredentialsProvider(credsProvider)
130
.build();
131
```
132
133
### SystemDefaultCredentialsProvider
134
135
```java { .api }
136
public class SystemDefaultCredentialsProvider implements CredentialsProvider {
137
public SystemDefaultCredentialsProvider();
138
public void setCredentials(AuthScope authscope, Credentials credentials);
139
public Credentials getCredentials(AuthScope authscope);
140
public void clear();
141
}
142
```
143
144
Credentials provider that uses system properties and default credentials.
145
146
## Authentication Schemes
147
148
### AuthScheme Interface
149
150
```java { .api }
151
public interface AuthScheme {
152
void processChallenge(Header header) throws MalformedChallengeException;
153
Header authenticate(Credentials credentials, HttpRequest request, HttpContext context) throws AuthenticationException;
154
String getSchemeName();
155
String getParameter(String name);
156
String getRealm();
157
boolean isConnectionBased();
158
boolean isComplete();
159
}
160
```
161
162
Base interface for authentication schemes.
163
164
### Authentication Scheme Registry
165
166
```java { .api }
167
public final class AuthSchemeRegistry {
168
public AuthSchemeRegistry();
169
public void register(String name, AuthSchemeFactory factory);
170
public void unregister(String name);
171
public AuthScheme getAuthScheme(String name, HttpParams params) throws IllegalStateException;
172
public List<String> getSchemeNames();
173
}
174
```
175
176
Registry for authentication scheme factories.
177
178
### Authentication Scheme Providers
179
180
```java { .api }
181
public interface AuthSchemeProvider {
182
AuthScheme create(HttpContext context);
183
}
184
```
185
186
Provider interface for creating authentication schemes.
187
188
```java
189
Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
190
.register("basic", new BasicSchemeFactory())
191
.register("digest", new DigestSchemeFactory())
192
.register("ntlm", new NTLMSchemeFactory())
193
.build();
194
195
CloseableHttpClient httpClient = HttpClients.custom()
196
.setDefaultAuthSchemeRegistry(authSchemeRegistry)
197
.build();
198
```
199
200
## Authentication Cache
201
202
### AuthCache Interface
203
204
```java { .api }
205
public interface AuthCache {
206
void put(HttpHost host, AuthScheme authScheme);
207
AuthScheme get(HttpHost host);
208
void remove(HttpHost host);
209
void clear();
210
}
211
```
212
213
Cache for storing authentication schemes by host.
214
215
### BasicAuthCache
216
217
```java { .api }
218
public class BasicAuthCache implements AuthCache {
219
public BasicAuthCache();
220
public void put(HttpHost host, AuthScheme authScheme);
221
public AuthScheme get(HttpHost host);
222
public void remove(HttpHost host);
223
public void clear();
224
}
225
```
226
227
Basic implementation of authentication cache.
228
229
```java
230
AuthCache authCache = new BasicAuthCache();
231
BasicScheme basicAuth = new BasicScheme();
232
authCache.put(new HttpHost("api.example.com", 80, "http"), basicAuth);
233
234
HttpClientContext context = HttpClientContext.create();
235
context.setAuthCache(authCache);
236
237
HttpGet httpGet = new HttpGet("http://api.example.com/protected");
238
CloseableHttpResponse response = httpClient.execute(httpGet, context);
239
```
240
241
## SSL/TLS Support
242
243
### SSLContext Configuration
244
245
```java { .api }
246
public class SSLContextBuilder {
247
public static SSLContextBuilder create();
248
public SSLContextBuilder useProtocol(String protocol);
249
public SSLContextBuilder setSecureRandom(SecureRandom secureRandom);
250
public SSLContextBuilder loadTrustMaterial(KeyStore truststore, TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException;
251
public SSLContextBuilder loadTrustMaterial(File file, char[] storePassword, TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException;
252
public SSLContextBuilder loadTrustMaterial(URL url, char[] storePassword, TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException;
253
public SSLContextBuilder loadKeyMaterial(KeyStore keystore, char[] keyPassword, PrivateKeyStrategy aliasStrategy) throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException;
254
public SSLContextBuilder loadKeyMaterial(File file, char[] storePassword, char[] keyPassword, PrivateKeyStrategy aliasStrategy) throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, CertificateException, IOException;
255
public SSLContext build() throws NoSuchAlgorithmException, KeyManagementException;
256
}
257
```
258
259
Builder for creating SSL contexts with custom trust and key material.
260
261
```java
262
SSLContext sslContext = SSLContextBuilder.create()
263
.loadTrustMaterial(new File("truststore.jks"), "password".toCharArray())
264
.loadKeyMaterial(new File("keystore.jks"), "password".toCharArray(), "keypassword".toCharArray())
265
.build();
266
267
CloseableHttpClient httpClient = HttpClients.custom()
268
.setSSLContext(sslContext)
269
.build();
270
```
271
272
### SSL Connection Socket Factory
273
274
```java { .api }
275
public class SSLConnectionSocketFactory implements LayeredConnectionSocketFactory {
276
public static final String TLS;
277
public static final String SSL;
278
public static SSLConnectionSocketFactory getSocketFactory();
279
public static SSLConnectionSocketFactory getSystemSocketFactory();
280
281
public SSLConnectionSocketFactory(SSLContext sslContext);
282
public SSLConnectionSocketFactory(SSLContext sslContext, HostnameVerifier hostnameVerifier);
283
public SSLConnectionSocketFactory(SSLContext sslContext, String[] supportedProtocols, String[] supportedCipherSuites, HostnameVerifier hostnameVerifier);
284
}
285
```
286
287
Socket factory for SSL/TLS connections with configurable protocols and cipher suites.
288
289
```java
290
SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(
291
sslContext,
292
new String[]{"TLSv1.2", "TLSv1.3"},
293
null,
294
SSLConnectionSocketFactory.getDefaultHostnameVerifier()
295
);
296
297
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
298
.register("http", PlainConnectionSocketFactory.getSocketFactory())
299
.register("https", sslConnectionFactory)
300
.build();
301
302
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
303
CloseableHttpClient httpClient = HttpClients.custom()
304
.setConnectionManager(cm)
305
.build();
306
```
307
308
### Hostname Verification
309
310
```java { .api }
311
public interface HostnameVerifier {
312
boolean verify(String hostname, SSLSession session);
313
}
314
```
315
316
Interface for hostname verification in SSL connections.
317
318
```java
319
HostnameVerifier hostnameVerifier = new HostnameVerifier() {
320
@Override
321
public boolean verify(String hostname, SSLSession session) {
322
// Custom hostname verification logic
323
return hostname.endsWith(".example.com");
324
}
325
};
326
327
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
328
sslContext,
329
hostnameVerifier
330
);
331
```
332
333
## Authentication Strategies
334
335
### AuthenticationStrategy Interface
336
337
```java { .api }
338
public interface AuthenticationStrategy {
339
boolean isAuthenticationRequested(HttpHost authhost, HttpResponse response, HttpContext context);
340
Queue<AuthOption> select(Map<String, Header> challenges, HttpHost authhost, HttpResponse response, HttpContext context) throws MalformedChallengeException;
341
void authSucceeded(HttpHost authhost, AuthScheme authScheme, HttpContext context);
342
void authFailed(HttpHost authhost, AuthScheme authScheme, HttpContext context);
343
}
344
```
345
346
Strategy interface for handling authentication challenges.
347
348
### Target and Proxy Authentication
349
350
```java { .api }
351
public class TargetAuthenticationStrategy implements AuthenticationStrategy;
352
public class ProxyAuthenticationStrategy implements AuthenticationStrategy;
353
```
354
355
Specific strategies for target server and proxy authentication.
356
357
## Authentication Context
358
359
### HttpClientContext
360
361
```java { .api }
362
public class HttpClientContext extends HttpCoreContext {
363
public static HttpClientContext create();
364
public void setCredentialsProvider(CredentialsProvider credentialsProvider);
365
public CredentialsProvider getCredentialsProvider();
366
public void setAuthCache(AuthCache authCache);
367
public AuthCache getAuthCache();
368
public void setAuthSchemeRegistry(Lookup<AuthSchemeProvider> authSchemeRegistry);
369
public Lookup<AuthSchemeProvider> getAuthSchemeRegistry();
370
}
371
```
372
373
HTTP context with authentication-specific properties.
374
375
```java
376
HttpClientContext context = HttpClientContext.create();
377
context.setCredentialsProvider(credentialsProvider);
378
context.setAuthCache(authCache);
379
380
HttpGet httpGet = new HttpGet("https://api.example.com/protected");
381
CloseableHttpResponse response = httpClient.execute(httpGet, context);
382
```
383
384
## Types
385
386
### AuthOption
387
388
```java { .api }
389
public final class AuthOption {
390
public AuthOption(AuthScheme authScheme, Credentials creds);
391
public AuthScheme getAuthScheme();
392
public Credentials getCredentials();
393
}
394
```
395
396
Represents an authentication option with scheme and credentials.
397
398
### AuthState
399
400
```java { .api }
401
public class AuthState {
402
public void reset();
403
public void setState(AuthProtocolState state);
404
public AuthProtocolState getState();
405
public void update(AuthScheme authScheme, Credentials creds);
406
public AuthScheme getAuthScheme();
407
public Credentials getCredentials();
408
public void invalidate();
409
public boolean isValid();
410
}
411
```
412
413
Maintains the state of an authentication process.
414
415
### Principal Classes
416
417
```java { .api }
418
public class BasicUserPrincipal implements Principal {
419
public BasicUserPrincipal(String username);
420
public String getName();
421
}
422
423
public class NTUserPrincipal implements Principal {
424
public NTUserPrincipal(String domain, String username);
425
public String getName();
426
public String getDomain();
427
public String getUsername();
428
}
429
```
430
431
Principal implementations for different authentication types.