Sub topic 13
Authentication: Authorization Headers and Authenticator
Assume Java 11 or later, basic HTTP methods and headers, and familiarity with checked exceptions. Authentication proves who the caller is. Authorization controls what that caller may access. Java HttpClient does not manage most API tokens for you, so your application must add the appropriate credentials.
Sending an authorization header
Many APIs use a bearer token. The token is sent in the Authorization request header:
String token = System.getenv("API_TOKEN");
HttpRequest request = HttpRequest.newBuilder(
URI.create("https://api.example.com/profile"))
.header("Authorization", "Bearer " + token)
.header("Accept", "application/json")
.GET()
.build();
HttpResponse<String> response =
client.send(request, HttpResponse.BodyHandlers.ofString());A token is a secret. Read it from an environment variable or a secret manager. Do not commit it to source code or print request headers in logs. Use HTTPS so the header is encrypted while it travels over the network.
Basic authentication uses a username and password. The value after Basic is Base64-encoded text, not encryption. HTTPS is still required:
String credentials = user + ":" + password;
String encoded = Base64.getEncoder().encodeToString(
credentials.getBytes(StandardCharsets.UTF_8));
HttpRequest request = HttpRequest.newBuilder(
URI.create("https://api.example.com/items"))
.header("Authorization", "Basic " + encoded)
.GET()
.build();An API may require a different scheme, such as an API key header. Follow that service's documentation rather than assuming every service uses Authorization.
Responding to an authentication challenge
Authenticator supplies credentials after a server or proxy challenges the client, commonly with a 401 Unauthorized response. It is useful for challenge-based Basic authentication. It does not automatically understand a bearer-token API.
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
if ("api.example.com".equalsIgnoreCase(getRequestingHost())) {
return new PasswordAuthentication(
System.getenv("API_USER"),
System.getenv("API_PASSWORD").toCharArray());
}
return null;
}
};
HttpClient client = HttpClient.newBuilder()
.authenticator(authenticator)
.build();
HttpRequest request = HttpRequest.newBuilder(
URI.create("https://api.example.com/private"))
.GET()
.build();
HttpResponse<String> response =
client.send(request, HttpResponse.BodyHandlers.ofString());Check the requesting host before returning credentials. Otherwise, a redirect or proxy challenge could cause credentials to go to an unintended destination. Also check the response status yourself. Authentication failure usually arrives as a normal 401 or 403 response, not as a Java exception.
Choosing an authentication approach
| Approach | Best use | Main concern |
|---|---|---|
| `Authorization` header | Bearer tokens and preemptive Basic authentication | Protect and scope the secret |
| `Authenticator` | Server or proxy challenge-based authentication | Restrict which hosts receive credentials |
The same HttpClient can be reused for requests that share its authentication configuration. Create a separate client when requests need different credentials or policies.
Exercise
Why is Base64 encoding a Basic authentication value not enough to protect the password?
Show answer
Base64 changes the representation but does not encrypt it. Use HTTPS to protect the header in transit.