Sub topic 14
Authentication: Authorization headers and Authenticator
This chapter assumes you can build an HttpClient and an HttpRequest, call send, and read the status code. It covers two ways to prove who you are to an HTTP API: setting an Authorization header yourself, and letting the client answer a challenge through an Authenticator.
How HTTP authentication works
A server that needs credentials answers an unauthenticated request with 401 Unauthorized and a WWW-Authenticate header. That header names a scheme, such as Basic or Bearer. The client then sends the request again with an Authorization header in that scheme. A proxy does the same with 407 and Proxy-Authenticate.
Most modern APIs skip the challenge. The caller attaches the credential to every request from the start. In HttpClient this is the simplest and most predictable approach.
| Approach | Who sends the credential | Extra round trip | Typical use |
|---|---|---|---|
| `Authorization` header on the request | Your code, on every request | No | Bearer tokens, API keys, Basic |
| `Authenticator` on the client | The client, after a 401 or 407 | Yes, one per challenge | Basic auth against servers or proxies that challenge |
Setting the Authorization header
HttpClient has no default headers. Each HttpRequest carries its own, so every request needs the credential.
A bearer token is sent as it is. Read it from the environment and never hard-code it:
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class BearerCall {
public static void main(String[] args) throws Exception {
String token = System.getenv("API_TOKEN");
if (token == null || token.isBlank()) {
throw new IllegalStateException("Set API_TOKEN first");
}
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.example.com/me"))
.header("Authorization", "Bearer " + token)
.header("Accept", "application/json")
.GET()
.build();
HttpResponse<String> response =
client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode());
}
}Basic authentication sends username:password encoded with Base64. Base64 is an encoding and not encryption, so use Basic only over HTTPS.
import java.nio.charset.StandardCharsets;
import java.util.Base64;
static String basicHeader(String user, String password) {
String raw = user + ":" + password;
String encoded = Base64.getEncoder()
.encodeToString(raw.getBytes(StandardCharsets.UTF_8));
return "Basic " + encoded;
}You then call .header("Authorization", basicHeader(user, password)) on the request builder.
Keeping the code tidy
Repeating the header on every request invites mistakes. A small factory method that returns a pre-configured builder keeps the credential in one place:
static HttpRequest.Builder authorized(String url, String token) {
return HttpRequest.newBuilder(URI.create(url))
.header("Authorization", "Bearer " + token);
}
HttpRequest req = authorized("https://api.example.com/items", token)
.timeout(java.time.Duration.ofSeconds(10))
.GET()
.build();Bearer tokens often expire. If yours does, call a method such as currentToken() each time you build a request, instead of capturing the token once at startup. That method can refresh the token when it is close to expiry. The client does not refresh tokens for you.
Using an Authenticator
java.net.Authenticator is a standard class that supplies a username and password on demand. You register it on the client builder:
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class BasicAuthenticatorDemo {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newBuilder()
.authenticator(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
if (getRequestorType() == RequestorType.SERVER
&& "httpbin.org".equals(getRequestingHost())) {
return new PasswordAuthentication("alice", "secret".toCharArray());
}
return null;
}
})
.build();
HttpRequest request = HttpRequest
.newBuilder(URI.create("https://httpbin.org/basic-auth/alice/secret"))
.GET()
.build();
HttpResponse<String> response =
client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode());
System.out.println(response.body());
}
}The demo credentials belong to a public test service. In real code, read them from the environment or a secrets store.
Inside getPasswordAuthentication you can call these methods to decide what to return:
getRequestorType()returnsSERVERorPROXY.getRequestingHost(),getRequestingURL()andgetRequestingScheme()identify who is asking and which scheme was requested.getRequestingPrompt()returns the realm from the challenge.
Returning null means "no credentials". The client then gives you the 401 response unchanged.
What happens on the wire
Your code makes one send call and sees only the final response. The first attempt is invisible to it, but it costs a network round trip.
Limits and gotchas
- Basic only. The JDK client's built-in challenge handling covers the
Basicscheme. ForBearer, OAuth 2.0, API keys, or schemes such as NTLM and Negotiate, set the header yourself or use a library. Test any other scheme against your JDK version before relying on it. - Extra round trip. An API that never challenges, or that returns
403or404for missing credentials, never triggers theAuthenticator. A server that does challenge will see two requests per call, at least for the first call to a given resource. - Retry cap. If the server keeps rejecting the credentials, the client stops after a few attempts. The default limit is 3, set by the system property
jdk.httpclient.auth.retrylimit. You then get the401as a normal response, with no exception. - Authenticator is per client. It applies to every request made through that client. If different requests need different identities, either check
getRequestingHost()andgetRequestingURL()inside the authenticator, or build separate clients. - A 401 is not an exception. As with every non-2xx status, check
statusCode(). A401with a bearer token usually means the token expired or is wrong. Refresh the token and retry once at the application level. - Redirects. If you enable redirects, check whether your JDK version forwards the
Authorizationheader to the redirected host. Do not assume it strips or keeps it. When you send secrets, call the final URL directly, or turn redirects off and handleLocationyourself. - Logging. Never print request headers or the full
HttpRequestin logs without removing theAuthorizationvalue. Tokens in logs are a common source of leaks.
Choosing an approach
Use the header when the API documents a token or key, which is the usual case today. Use an Authenticator when you must talk to an older server or a proxy that sends Basic challenges, or when you want credential lookup in one place instead of in every request. For OAuth 2.0 token acquisition and refresh, HttpClient offers nothing built in. You call the token endpoint yourself, store the token with its expiry, and attach it with the header approach above.
Exercise
An API returns 401 for your first request. You registered an Authenticator on the client, but your code still receives a 401 response, and send throws no exception. Give two likely causes.
Show answer
First, the Authenticator returned null. This happens when its host or requestor-type checks do not match, so no credentials were supplied. Second, the server rejected the credentials after the client's retry limit (3 by default). It could also be that the server uses a scheme the client does not handle, such as Bearer, so no challenge handling runs. In every case the 401 comes back as a normal HttpResponse, so you must check statusCode().
Exercise
Why would you choose an Authorization header over an Authenticator for a REST API that uses expiring bearer tokens?
Show answer
The header is sent on the first request, so there is no extra 401 round trip. Also, the Authenticator mechanism only answers Basic challenges, and it cannot refresh tokens. With a header you can fetch a current token each time you build the request.