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:
| Authentication | Typical Use |
|---|---|
| API Key | Simple service access |
| Bearer Token | Authenticated API calls |
| OAuth 2.0 | Delegated or service authorization |
| JWT | Token format often used with OAuth/auth systems |
These concepts can overlap.
For example:
OAuth 2.0
↓
returns access token
↓
access token happens to be JWT
↓
sent as Bearer token
37. Secure Secret Storage
Avoid putting secrets in:
source code
GitHub repositories
README files
Dockerfiles
frontend JavaScript
logs
error messages
Better options include:
environment variables
secret managers
container secrets
cloud provider secret stores
CI/CD secret stores
38. Environment Variable Example
String clientId =
System.getenv(
"OAUTH_CLIENT_ID"
);
String clientSecret =
System.getenv(
"OAUTH_CLIENT_SECRET"
);
Validate them:
if (clientId == null ||
clientSecret == null) {
throw new IllegalStateException(
"OAuth credentials are missing"
);
}
39. Don't Print Secrets
This is dangerous:
System.out.println(
"Token: " + token
);
Also dangerous:
System.out.println(
request.headers()
);
because the headers may contain:
Authorization
Instead, log only safe information:
System.out.println(
request.method() +
" " +
request.uri()
);
40. Redact Sensitive Headers
If you need to log headers, redact secrets.
Conceptually:
Authorization: Bearer ***
X-API-Key: ***
Never log:
Authorization: Bearer actual-token-here
41. Don't Put Tokens in URLs
Avoid:
https://api.example.com/users?token=SECRET
URLs can appear in:
logs
browser history
proxy logs
analytics
monitoring tools
Prefer headers:
Authorization: Bearer TOKEN
42. HTTPS Is Mandatory
Authentication tokens should only be sent over HTTPS.
Avoid:
http://api.example.com
Use:
https://api.example.com
Without TLS, credentials may be exposed in transit.
43. Token Scope
OAuth tokens may have scopes.
For example:
users.read
users.write
orders.read
A good security principle is:
grant only what is needed
If your client only reads users, avoid asking for:
admin.full_access
when:
users.read
is enough.
This is the principle of least privilege.
44. Short-Lived Tokens Are Better
Long-lived credentials are more dangerous if stolen.
A common security pattern is:
long-lived client credential
↓
authorization server
↓
short-lived access token
↓
API
If an access token leaks, its usefulness is limited by expiration.
45. Token Caching
You should normally avoid requesting a new OAuth token for every API call.
Bad:
Get token
Call API
Get token
Call API
Get token
Call API
Better:
Get token
↓
cache it
↓
Call API
Call API
Call API
↓
token almost expired
↓
get new token
This reduces unnecessary authorization-server traffic.
46. Thread Safety Matters
Suppose many threads call:
getToken()
at the same time when the token expires.
Without synchronization:
Thread 1 → requests new token
Thread 2 → requests new token
Thread 3 → requests new token
Thread 4 → requests new token
That is wasteful.
Using:
synchronized
around refresh logic can prevent multiple simultaneous refreshes.
47. Thread-Safe Token Provider
public synchronized String getToken()
throws IOException,
InterruptedException {
if (cachedToken == null ||
cachedToken.isExpired()) {
cachedToken =
fetchToken();
}
return cachedToken.value();
}
Now one thread refreshes while others wait.
48. Full OAuthTokenProvider
Here is a more complete example:
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
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();
}
@Override
public synchronized void invalidate() {
cachedToken = null;
}
private AccessToken fetchToken()
throws IOException,
InterruptedException {
String body =
"grant_type=client_credentials" +
"&client_id=" +
encode(clientId) +
"&client_secret=" +
encode(clientSecret);
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()
);
}
TokenResponse tokenResponse =
mapper.readValue(
response.body(),
TokenResponse.class
);
Instant expiresAt =
Instant.now()
.plusSeconds(
tokenResponse.expiresIn()
);
return new AccessToken(
tokenResponse.accessToken(),
expiresAt
);
}
private String encode(
String value
) {
return URLEncoder.encode(
value,
StandardCharsets.UTF_8
);
}
}
49. AccessToken Record
import java.time.Instant;
public record AccessToken(
String value,
Instant expiresAt
) {
public boolean isExpired() {
return Instant.now()
.plusSeconds(30)
.isAfter(
expiresAt
);
}
}
The 30-second buffer helps avoid using a token that is about to expire.
50. TokenResponse
import com.fasterxml.jackson.annotation.JsonProperty;
public record TokenResponse(
@JsonProperty("access_token")
String accessToken,
@JsonProperty("token_type")
String tokenType,
@JsonProperty("expires_in")
long expiresIn
) {
}
51. TokenProvider
import java.io.IOException;
public interface TokenProvider {
String getToken()
throws IOException,
InterruptedException;
void invalidate();
}
52. Authenticated REST Client
Now we can create:
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;
}
public <T> T get(
String url,
Class<T> responseType
) throws IOException,
InterruptedException {
HttpResponse<String> response =
sendGet(url);
if (response.statusCode() < 200 ||
response.statusCode() >= 300) {
throw new ApiException(
response.statusCode(),
response.body()
);
}
return mapper.readValue(
response.body(),
responseType
);
}
private HttpResponse<String> sendGet(
String url
) throws IOException,
InterruptedException {
HttpResponse<String> response =
sendGetOnce(url);
if (response.statusCode() != 401) {
return response;
}
tokenProvider.invalidate();
return sendGetOnce(url);
}
private HttpResponse<String> sendGetOnce(
String url
) throws IOException,
InterruptedException {
String token =
tokenProvider.getToken();
HttpRequest request =
HttpRequest.newBuilder()
.uri(
URI.create(url)
)
.header(
"Accept",
"application/json"
)
.header(
"Authorization",
"Bearer " + token
)
.GET()
.build();
return client.send(
request,
HttpResponse.BodyHandlers.ofString()
);
}
}
Now the application code stays simple.
53. Using the Client
Load secrets:
String clientId =
System.getenv(
"OAUTH_CLIENT_ID"
);
String clientSecret =
System.getenv(
"OAUTH_CLIENT_SECRET"
);
Create the token provider:
TokenProvider tokenProvider =
new OAuthTokenProvider(
"https://auth.example.com/oauth/token",
clientId,
clientSecret
);
Create the REST client:
RestClient client =
new RestClient(
tokenProvider
);
Call the API:
User user =
client.get(
"https://api.example.com/users/10",
User.class
);
The calling code does not need to manage tokens manually.
54. Support API Keys with the Same Design
We can make the authentication strategy even more generic.
Create:
public interface AuthProvider {
void apply(
HttpRequest.Builder builder
) throws IOException,
InterruptedException;
}
API key implementation:
public class ApiKeyAuthProvider
implements AuthProvider {
private final String apiKey;
public ApiKeyAuthProvider(
String apiKey
) {
this.apiKey =
apiKey;
}
@Override
public void apply(
HttpRequest.Builder builder
) {
builder.header(
"X-API-Key",
apiKey
);
}
}
55. Bearer Token Auth Provider
public class BearerAuthProvider
implements AuthProvider {
private final TokenProvider tokenProvider;
public BearerAuthProvider(
TokenProvider tokenProvider
) {
this.tokenProvider =
tokenProvider;
}
@Override
public void apply(
HttpRequest.Builder builder
) throws IOException,
InterruptedException {
builder.header(
"Authorization",
"Bearer " +
tokenProvider.getToken()
);
}
}
Now the REST client no longer cares which authentication mechanism is used.
56. The Strategy Pattern
Our architecture becomes:
RestClient
↓
AuthProvider
↓
┌─────────────────────┐
│ API Key │
│ Bearer Token │
│ OAuth Token Provider│
└─────────────────────┘
This is essentially the Strategy pattern.
The REST client delegates authentication behavior to another object.
57. Generic Authenticated Request Builder
private HttpRequest.Builder requestBuilder(
String url
) throws IOException,
InterruptedException {
HttpRequest.Builder builder =
HttpRequest.newBuilder()
.uri(
URI.create(url)
)
.header(
"Accept",
"application/json"
);
authProvider.apply(
builder
);
return builder;
}
Now authentication is centralized.
58. Public API Client
We can also support no authentication.
public class NoAuthProvider
implements AuthProvider {
@Override
public void apply(
HttpRequest.Builder builder
) {
// nothing
}
}
Now the same REST client works for:
Public API
API key API
Bearer-token API
OAuth API
59. Refresh Tokens
Some OAuth flows provide:
{
"access_token": "...",
"refresh_token": "...",
"expires_in": 3600
}
The refresh token can be used to obtain a new access token without making the user sign in again.
Conceptually:
Access token expires
↓
Refresh token
↓
Token endpoint
↓
New access token
60. Refresh Token Request
A request may look like:
grant_type=refresh_token
&refresh_token=...
&client_id=...
The exact format depends on the authorization server.
Never assume all providers behave identically.
61. Protect Refresh Tokens Carefully
Refresh tokens can be more sensitive than access tokens because they may remain valid much longer.
Treat them like credentials.
Avoid:
logs
source code
client-side storage without protection
URLs
debug output
62. 401 vs 403
These two are commonly confused.
401 Unauthorized
Usually means:
authentication is missing or invalid
Examples:
expired token
invalid token
missing credentials
403 Forbidden
Usually means:
you are authenticated,
but you are not allowed to do this
Example:
token has users.read
but endpoint requires users.delete
A typical rule:
401
→ authentication problem
403
→ permission problem
63. Don't Automatically Refresh on 403
Refreshing an access token usually does not fix missing permissions.
If the API returns:
403 Forbidden
and the token lacks the required scope, getting another identical token will not help.
So:
401
→ maybe refresh once
403
→ usually fail
64. Authentication Error Handling
A reasonable approach:
400
→ request problem
401
→ refresh once if appropriate
403
→ insufficient permission
429
→ rate limit handling
5xx
→ retry policy
Authentication is only one part of your broader error-handling strategy.
65. Combine Auth with Production Retry Logic
From our previous REST client article, we had retry logic for:
429
500
502
503
504
Authentication should fit around that.
For example:
Send request
↓
401?
↓ yes
Refresh token once
↓
Retry request
↓
429 or 5xx?
↓
Apply retry/backoff rules
But keep bounded retries.
66. Avoid Retry Loops Between Auth and Network Logic
Imagine:
401
→ refresh
→ 503
→ retry
→ 401
→ refresh
→ 503
→ retry
Without limits, logic can become unpredictable.
Track:
authentication retries
network retries
separately and cap both.
67. Security Checklist
Before shipping an authenticated REST client, check:
✓ Are secrets outside source code?
✓ Are tokens excluded from logs?
✓ Is HTTPS always used?
✓ Are access tokens short-lived?
✓ Are tokens cached appropriately?
✓ Are tokens refreshed before expiration?
✓ Is refresh limited after 401?
✓ Are 403 responses treated differently from 401?
✓ Are scopes minimal?
✓ Are refresh tokens protected?
✓ Is token refresh thread-safe?
✓ Are secrets kept out of URLs?
✓ Are authentication retries bounded?
✓ Are credentials rotated when exposed?
68. Common Mistakes
Mistake 1: Hardcoding secrets
String token =
"secret-token";
Mistake 2: Logging tokens
System.out.println(
"Authorization: Bearer " +
token
);
Mistake 3: Putting tokens in URLs
/api/users?token=secret
Mistake 4: Requesting a new token for every API call
token
request
token
request
token
request
Mistake 5: Retrying 401 forever
401
refresh
401
refresh
401
refresh...
Mistake 6: Treating decoded JWTs as verified JWTs
decoded ≠ trusted
Mistake 7: Asking for excessive OAuth scopes
admin.*
when:
users.read
would be enough.
69. A Clean Architecture
A production-ready client might look like:
Application
↓
API-specific client
↓
RestClient
↓
AuthProvider
↓
TokenProvider
↓
Authorization Server
And separately:
RestClient
↓
HttpClient
↓
External REST API
Each component has a clear responsibility.
70. Responsibilities
HttpClient
Handles HTTP communication.
ObjectMapper
Handles JSON.
TokenProvider
Obtains and caches tokens.
AuthProvider
Applies authentication to requests.
RestClient
Handles HTTP + serialization + errors.
API-specific client
Knows endpoints and domain models.
Application
Works with normal Java objects.
71. Quick Cheat Sheet
API Key
.header(
"X-API-Key",
apiKey
)
Bearer Token
.header(
"Authorization",
"Bearer " + token
)
Environment Variable
String token =
System.getenv(
"ACCESS_TOKEN"
);
Client Credentials Grant
grant_type=client_credentials
Token Expiration
Instant expiresAt =
Instant.now()
.plusSeconds(
expiresIn
);
Refresh Before Expiration
Instant.now()
.plusSeconds(30)
.isAfter(
expiresAt
);
Handle 401
invalidate token
↓
get new token
↓
retry once
403
usually do not refresh
72. The Mental Model
The simplest authentication flow is:
Application
↓
Credentials
↓
Authorization server
↓
Access token
↓
REST client
↓
Authorization: Bearer TOKEN
↓
API
When the token expires:
Token expired
↓
TokenProvider
↓
Request new token
↓
Cache token
↓
Continue API calls
The rest of the application should ideally never need to manage this directly.
Final Thoughts
Authentication code often starts very simply:
.header(
"Authorization",
"Bearer " + token
)
But production systems quickly introduce more concerns:
token expiration
refresh
caching
thread safety
scope
secret storage
401 handling
logging
HTTPS
The best approach is to keep these responsibilities separated.
A clean architecture might look like:
Application
↓
API Client
↓
RestClient
↓
AuthProvider
↓
TokenProvider
That allows your application code to remain simple:
User user =
userApi.getUser(10);
while the lower layers handle:
OAuth
tokens
headers
refresh
authentication errors
HTTP
JSON
The goal is not just to make authenticated requests work.
The goal is to make authentication predictable, reusable, and difficult to misuse.
About the Author
Deividas Strole is a Full-Stack Developer based in California, specializing in Java, Spring Boot, JavaScript, React, SQL, and AI-powered applications. He writes about software engineering, modern full-stack development, and digital marketing.
Connect with me:
Top comments (0)