Most REST APIs require some form of authentication.
Sometimes that is as simple as an API key.
Sometimes it means sending a bearer token.
And in more complex systems, you may need OAuth 2.0, JWTs, token refresh, or short-lived credentials.
In this tutorial, we'll build on Java's built-in HttpClient and create practical authentication patterns for REST API clients.
We'll cover:
- API key authentication
- Bearer tokens
- OAuth 2.0 basics
- OAuth 2.0 Client Credentials flow
- JWT basics
- Token expiration
- Token refresh
- Secure token storage
- Environment variables
- Avoiding secret leakage in logs
- Handling
401 Unauthorized - Reusable authentication helpers
- Designing a secure REST client
By the end, you'll have a cleaner and safer approach to authenticated HTTP requests in Java.
1. Authentication vs Authorization
These two terms are often mixed together.
Authentication
Authentication answers:
Who are you? For example:
API key username/password access token JWT Authorization
Authorization answers:
What are you allowed to do? For example:
read users create orders delete records access admin endpoints So:
Authentication → identity Authorization → permissions 2. The Simplest Case: API Keys
Many APIs use an API key.
A request might look like this:
GET /weather X-API-Key: abc123 Or:
Authorization: ApiKey abc123 The exact format depends on the API.
With Java HttpClient:
String apiKey = "abc123"; HttpRequest request = HttpRequest.newBuilder() .uri(URI.create( "https://api.example.com/weather" )) .header( "X-API-Key", apiKey ) .GET() .build(); Simple enough.
But there is an immediate problem.
3. Don't Hardcode API Keys
Avoid this:
String apiKey = "abc123-super-secret-key"; especially inside source code committed to Git.
Once a secret enters Git history, removing it completely can be difficult.
A better option is an environment variable.
String apiKey = System.getenv("API_KEY"); Now the value lives outside the application source.
4. Validate Required Secrets
If the environment variable is missing, fail early.
String apiKey = System.getenv("API_KEY"); if (apiKey == null || apiKey.isBlank()) { throw new IllegalStateException( "API_KEY environment variable is not set" ); } This is better than allowing a request to fail later with an unclear authentication error.
5. Bearer Token Authentication
Many REST APIs use bearer tokens.
The HTTP header looks like this:
Authorization: Bearer TOKEN In Java:
String token = System.getenv("ACCESS_TOKEN"); HttpRequest request = HttpRequest.newBuilder() .uri( URI.create( "https://api.example.com/users" ) ) .header( "Authorization", "Bearer " + token ) .GET() .build(); Conceptually:
Application ↓ Bearer token ↓ Authorization header ↓ API 6. Reuse Authentication Logic
You probably don't want to repeat:
.header( "Authorization", "Bearer " + token ) everywhere.
Instead, create a helper:
private HttpRequest.Builder requestBuilder( String url ) { return HttpRequest.newBuilder() .uri( URI.create(url) ) .header( "Accept", "application/json" ) .header( "Authorization", "Bearer " + token ); } Then:
HttpRequest request = requestBuilder(url) .GET() .build(); Much cleaner.
7. Make Authentication Optional
Some endpoints may be public.
So we can make the token optional:
private HttpRequest.Builder requestBuilder( String url ) { HttpRequest.Builder builder = HttpRequest.newBuilder() .uri( URI.create(url) ) .header( "Accept", "application/json" ); if (token != null && !token.isBlank()) { builder.header( "Authorization", "Bearer " + token ); } return builder; } Now the same client can work with authenticated and public endpoints.
8. What Is OAuth 2.0?
OAuth 2.0 is an authorization framework.
It allows an application to obtain an access token and use that token to call an API.
A simplified flow looks like this:
Application ↓ Authorization Server ↓ Access Token ↓ REST API Instead of repeatedly sending a username and password to the API, the application sends an access token.
9. OAuth 2.0 Access Tokens
A typical API request looks like:
Authorization: Bearer eyJ... The application first obtains the token from an authorization server.
Then it sends that token with API requests.
Conceptually:
1. Get token Application ↓ Token Endpoint ↓ Access Token 2. Call API Application ↓ Bearer Access Token ↓ REST API 10. Common OAuth 2.0 Flows
OAuth 2.0 supports several authorization patterns.
Common examples include:
Authorization Code Client Credentials Device Authorization Refresh Token Which one you use depends on the application.
11. Authorization Code Flow
Authorization Code is commonly used when a user signs into an application.
Conceptually:
User ↓ Login / Consent ↓ Authorization Server ↓ Authorization Code ↓ Application ↓ Token Endpoint ↓ Access Token This is common for web and mobile applications acting on behalf of users.
12. Client Credentials Flow
For server-to-server communication, the Client Credentials flow is often more relevant.
There may be no user involved at all.
Example:
Backend Service A ↓ Backend Service B Service A authenticates itself using:
client_id client_secret and receives an access token.
13. Client Credentials Request
A token request commonly looks similar to:
POST /oauth/token Content-Type: application/x-www-form-urlencoded grant_type=client_credentials &client_id=... &client_secret=... Some authorization servers instead use HTTP Basic authentication for the client ID and secret.
Always follow the specific provider's documentation.
14. Form-Encoded Request Body
OAuth token endpoints often expect:
application/x-www-form-urlencoded not JSON.
We can build the body:
String body = "grant_type=client_credentials" + "&client_id=" + URLEncoder.encode( clientId, StandardCharsets.UTF_8 ) + "&client_secret=" + URLEncoder.encode( clientSecret, StandardCharsets.UTF_8 ); Then send it:
HttpRequest request = HttpRequest.newBuilder() .uri( URI.create(tokenUrl) ) .header( "Content-Type", "application/x-www-form-urlencoded" ) .POST( HttpRequest.BodyPublishers .ofString(body) ) .build(); 15. OAuth Token Response
A token response may look like this:
{ "access_token": "eyJ...", "token_type": "Bearer", "expires_in": 3600 } We can represent that with a Java record:
public record TokenResponse( String access_token, String token_type, long expires_in ) { } However, Java naming conventions normally prefer camelCase.
So we can use Jackson annotations.
16. Cleaner Token Model with Jackson
import com.fasterxml.jackson.annotation.JsonProperty; public record TokenResponse( @JsonProperty("access_token") String accessToken, @JsonProperty("token_type") String tokenType, @JsonProperty("expires_in") long expiresIn ) { } Now:
"access_token" maps to:
accessToken() 17. Request an OAuth Token
Let's combine everything.
public TokenResponse requestToken( String tokenUrl, String clientId, String clientSecret ) throws IOException, InterruptedException { String body = "grant_type=client_credentials" + "&client_id=" + URLEncoder.encode( clientId, StandardCharsets.UTF_8 ) + "&client_secret=" + URLEncoder.encode( clientSecret, StandardCharsets.UTF_8 ); HttpRequest request = HttpRequest.newBuilder() .uri( URI.create(tokenUrl) ) .header( "Content-Type", "application/x-www-form-urlencoded" ) .POST( HttpRequest.BodyPublishers .ofString(body) ) .build(); HttpResponse<String> response = client.send( request, HttpResponse.BodyHandlers.ofString() ); if (response.statusCode() < 200 || response.statusCode() >= 300) { throw new ApiException( response.statusCode(), response.body() ); } return mapper.readValue( response.body(), TokenResponse.class ); } Now:
TokenResponse token = requestToken( tokenUrl, clientId, clientSecret ); 18. Use the Access Token
Once we have:
token.accessToken() we can call the API:
HttpRequest request = HttpRequest.newBuilder() .uri( URI.create(apiUrl) ) .header( "Authorization", "Bearer " + token.accessToken() ) .GET() .build(); 19. Tokens Expire
Access tokens are often short-lived.
For example:
{ "expires_in": 3600 } That means:
3600 seconds = 1 hour You should not assume a token lasts forever.
20. Track Token Expiration
We can create a cached token:
public record AccessToken( String value, Instant expiresAt ) { public boolean isExpired() { return Instant.now() .isAfter( expiresAt ); } } When the token arrives:
Instant expiresAt = Instant.now() .plusSeconds( tokenResponse.expiresIn() ); Then:
AccessToken token = new AccessToken( tokenResponse.accessToken(), expiresAt ); 21. Refresh Before Expiration
It is usually better not to wait until the exact expiration moment.
Network latency and clock differences can cause problems.
Use a buffer.
For example:
public boolean isExpired() { return Instant.now() .plusSeconds(30) .isAfter( expiresAt ); } Now the application treats the token as expired 30 seconds early.
22. Create a Token Provider
Instead of letting your REST client manage token details directly, create a separate component.
public interface TokenProvider { String getToken() throws IOException, InterruptedException; } Then create an OAuth implementation.
23. OAuth Token Provider
public class OAuthTokenProvider implements TokenProvider { private final HttpClient client; private final ObjectMapper mapper; private final String tokenUrl; private final String clientId; private final String clientSecret; private AccessToken cachedToken; public OAuthTokenProvider( String tokenUrl, String clientId, String clientSecret ) { this.client = HttpClient.newHttpClient(); this.mapper = new ObjectMapper(); this.tokenUrl = tokenUrl; this.clientId = clientId; this.clientSecret = clientSecret; } @Override public synchronized String getToken() throws IOException, InterruptedException { if (cachedToken == null || cachedToken.isExpired()) { cachedToken = fetchToken(); } return cachedToken.value(); } private AccessToken fetchToken() throws IOException, InterruptedException { // request token here return null; } } The REST client no longer needs to know how OAuth works.
It simply asks:
tokenProvider.getToken() 24. Why Separate Token Logic?
This architecture is cleaner:
RestClient ↓ TokenProvider ↓ OAuth server The REST client knows:
"I need a token." It does not need to know:
how tokens are requested how they expire how they refresh where client credentials are stored That separation is useful.
25. Add the Token Provider to the REST Client
public class RestClient { private final HttpClient client; private final ObjectMapper mapper; private final TokenProvider tokenProvider; public RestClient( TokenProvider tokenProvider ) { this.client = HttpClient.newHttpClient(); this.mapper = new ObjectMapper(); this.tokenProvider = tokenProvider; } } Then:
private HttpRequest.Builder requestBuilder( String url ) throws IOException, InterruptedException { String token = tokenProvider.getToken(); return HttpRequest.newBuilder() .uri( URI.create(url) ) .header( "Accept", "application/json" ) .header( "Authorization", "Bearer " + token ); } 26. Handle 401 Unauthorized
Suppose your token expires unexpectedly.
The server may respond:
401 Unauthorized A naive client may simply fail.
A better design may:
401 ↓ invalidate cached token ↓ request new token ↓ retry once But be careful.
27. Don't Retry 401 Forever
Never do:
401 ↓ refresh ↓ 401 ↓ refresh ↓ 401 ↓ refresh forever Limit authentication retries.
A good pattern is:
first 401 → refresh token → retry once second 401 → fail 28. Add Token Invalidation
Update the interface:
public interface TokenProvider { String getToken() throws IOException, InterruptedException; void invalidate(); } Implementation:
@Override public synchronized void invalidate() { cachedToken = null; } Now the REST client can force a refresh after a 401.
29. Retry Once After 401
Example:
private HttpResponse<String> sendAuthenticated( String url ) throws IOException, InterruptedException { HttpRequest request = buildAuthenticatedRequest(url); HttpResponse<String> response = client.send( request, HttpResponse.BodyHandlers.ofString() ); if (response.statusCode() != 401) { return response; } tokenProvider.invalidate(); HttpRequest retryRequest = buildAuthenticatedRequest(url); return client.send( retryRequest, HttpResponse.BodyHandlers.ofString() ); } This is much safer than unlimited refresh attempts.
30. What Is a JWT?
JWT stands for:
JSON Web Token A JWT commonly looks like:
xxxxx.yyyyy.zzzzz It contains three sections:
header.payload.signature For example:
eyJhbGciOi... . eyJzdWIiOi... . SflKxwRJS... 31. JWT Structure
A JWT contains:
Header ↓ Algorithm and token metadata Payload ↓ Claims Signature ↓ Integrity verification A payload might include claims such as:
{ "sub": "12345", "iss": "https://auth.example.com", "exp": 1760000000, "scope": "users.read" } 32. Important: JWT Does Not Automatically Mean Encryption
This is a common misunderstanding.
JWT payloads are often encoded, not encrypted.
That means someone who sees the token may be able to decode the claims.
So do not put secrets into a JWT payload just because it looks unreadable.
Think of many JWTs as:
signed not necessarily:
encrypted 33. JWT Expiration
A JWT may contain:
exp which means expiration time.
Example:
{ "exp": 1760000000 } The API should reject an expired token.
Your client should still rely on the authorization server's token lifetime rather than inventing its own.
34. Do You Need to Decode JWTs?
Often, no.
If your application simply receives an access token and forwards it to an API:
Authorization Server ↓ JWT access token ↓ Your application ↓ API your application may not need to inspect the JWT at all.
It can treat it as an opaque token.
That is often simpler and safer.
35. JWT Verification Is Different from Decoding
Anyone can decode the Base64URL payload.
Verification is different.
Verification checks the signature and validates claims.
A secure JWT verification process may need to check:
signature issuer audience expiration not-before time algorithm Do not treat:
"I successfully decoded the token" as:
"The token is valid" They are not the same thing.
36. API Key vs Bearer Token vs OAuth
A simplified comparison:
