DEV Community

Cover image for Building a Java REST Client with OAuth 2.0, JWT, API Keys, and Secure Token Handling
Deividas Strole
Deividas Strole

Posted on

Building a Java REST Client with OAuth 2.0, JWT, API Keys, and Secure Token Handling

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?
Enter fullscreen mode Exit fullscreen mode

For example:

API key
username/password
access token
JWT
Enter fullscreen mode Exit fullscreen mode

Authorization

Authorization answers:

What are you allowed to do?
Enter fullscreen mode Exit fullscreen mode

For example:

read users
create orders
delete records
access admin endpoints
Enter fullscreen mode Exit fullscreen mode

So:

Authentication
    → identity

Authorization
    → permissions
Enter fullscreen mode Exit fullscreen mode

2. The Simplest Case: API Keys

Many APIs use an API key.

A request might look like this:

GET /weather

X-API-Key: abc123
Enter fullscreen mode Exit fullscreen mode

Or:

Authorization: ApiKey abc123
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

Simple enough.

But there is an immediate problem.


3. Don't Hardcode API Keys

Avoid this:

String apiKey =
        "abc123-super-secret-key";
Enter fullscreen mode Exit fullscreen mode

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");
Enter fullscreen mode Exit fullscreen mode

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"
    );
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

Conceptually:

Application
    ↓
Bearer token
    ↓
Authorization header
    ↓
API
Enter fullscreen mode Exit fullscreen mode

6. Reuse Authentication Logic

You probably don't want to repeat:

.header(
    "Authorization",
    "Bearer " + token
)
Enter fullscreen mode Exit fullscreen mode

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
            );
}
Enter fullscreen mode Exit fullscreen mode

Then:

HttpRequest request =
        requestBuilder(url)
                .GET()
                .build();
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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...
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

10. Common OAuth 2.0 Flows

OAuth 2.0 supports several authorization patterns.

Common examples include:

Authorization Code
Client Credentials
Device Authorization
Refresh Token
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Service A authenticates itself using:

client_id
client_secret
Enter fullscreen mode Exit fullscreen mode

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=...
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
        );
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

15. OAuth Token Response

A token response may look like this:

{
  "access_token": "eyJ...",
  "token_type": "Bearer",
  "expires_in": 3600
}
Enter fullscreen mode Exit fullscreen mode

We can represent that with a Java record:

public record TokenResponse(
        String access_token,
        String token_type,
        long expires_in
) {
}
Enter fullscreen mode Exit fullscreen mode

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
) {
}
Enter fullscreen mode Exit fullscreen mode

Now:

"access_token"
Enter fullscreen mode Exit fullscreen mode

maps to:

accessToken()
Enter fullscreen mode Exit fullscreen mode

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
    );
}
Enter fullscreen mode Exit fullscreen mode

Now:

TokenResponse token =
        requestToken(
                tokenUrl,
                clientId,
                clientSecret
        );
Enter fullscreen mode Exit fullscreen mode

18. Use the Access Token

Once we have:

token.accessToken()
Enter fullscreen mode Exit fullscreen mode

we can call the API:

HttpRequest request =
        HttpRequest.newBuilder()
                .uri(
                        URI.create(apiUrl)
                )
                .header(
                        "Authorization",
                        "Bearer " +
                        token.accessToken()
                )
                .GET()
                .build();
Enter fullscreen mode Exit fullscreen mode

19. Tokens Expire

Access tokens are often short-lived.

For example:

{
  "expires_in": 3600
}
Enter fullscreen mode Exit fullscreen mode

That means:

3600 seconds
=
1 hour
Enter fullscreen mode Exit fullscreen mode

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
                );
    }
}
Enter fullscreen mode Exit fullscreen mode

When the token arrives:

Instant expiresAt =
        Instant.now()
                .plusSeconds(
                        tokenResponse.expiresIn()
                );
Enter fullscreen mode Exit fullscreen mode

Then:

AccessToken token =
        new AccessToken(
                tokenResponse.accessToken(),
                expiresAt
        );
Enter fullscreen mode Exit fullscreen mode

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
            );
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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;
    }
}
Enter fullscreen mode Exit fullscreen mode

The REST client no longer needs to know how OAuth works.

It simply asks:

tokenProvider.getToken()
Enter fullscreen mode Exit fullscreen mode

24. Why Separate Token Logic?

This architecture is cleaner:

RestClient
    ↓
TokenProvider
    ↓
OAuth server
Enter fullscreen mode Exit fullscreen mode

The REST client knows:

"I need a token."
Enter fullscreen mode Exit fullscreen mode

It does not need to know:

how tokens are requested
how they expire
how they refresh
where client credentials are stored
Enter fullscreen mode Exit fullscreen mode

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;
    }
}
Enter fullscreen mode Exit fullscreen mode

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
            );
}
Enter fullscreen mode Exit fullscreen mode

26. Handle 401 Unauthorized

Suppose your token expires unexpectedly.

The server may respond:

401 Unauthorized
Enter fullscreen mode Exit fullscreen mode

A naive client may simply fail.

A better design may:

401
    ↓
invalidate cached token
    ↓
request new token
    ↓
retry once
Enter fullscreen mode Exit fullscreen mode

But be careful.


27. Don't Retry 401 Forever

Never do:

401
    ↓
refresh
    ↓
401
    ↓
refresh
    ↓
401
    ↓
refresh forever
Enter fullscreen mode Exit fullscreen mode

Limit authentication retries.

A good pattern is:

first 401
    → refresh token
    → retry once

second 401
    → fail
Enter fullscreen mode Exit fullscreen mode

28. Add Token Invalidation

Update the interface:

public interface TokenProvider {

    String getToken()
            throws IOException,
                   InterruptedException;

    void invalidate();
}
Enter fullscreen mode Exit fullscreen mode

Implementation:

@Override
public synchronized void invalidate() {
    cachedToken = null;
}
Enter fullscreen mode Exit fullscreen mode

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()
    );
}
Enter fullscreen mode Exit fullscreen mode

This is much safer than unlimited refresh attempts.


30. What Is a JWT?

JWT stands for:

JSON Web Token
Enter fullscreen mode Exit fullscreen mode

A JWT commonly looks like:

xxxxx.yyyyy.zzzzz
Enter fullscreen mode Exit fullscreen mode

It contains three sections:

header.payload.signature
Enter fullscreen mode Exit fullscreen mode

For example:

eyJhbGciOi...
.
eyJzdWIiOi...
.
SflKxwRJS...
Enter fullscreen mode Exit fullscreen mode

31. JWT Structure

A JWT contains:

Header
    ↓
Algorithm and token metadata

Payload
    ↓
Claims

Signature
    ↓
Integrity verification
Enter fullscreen mode Exit fullscreen mode

A payload might include claims such as:

{
  "sub": "12345",
  "iss": "https://auth.example.com",
  "exp": 1760000000,
  "scope": "users.read"
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

not necessarily:

encrypted
Enter fullscreen mode Exit fullscreen mode

33. JWT Expiration

A JWT may contain:

exp
Enter fullscreen mode Exit fullscreen mode

which means expiration time.

Example:

{
  "exp": 1760000000
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Do not treat:

"I successfully decoded the token"
Enter fullscreen mode Exit fullscreen mode

as:

"The token is valid"
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

37. Secure Secret Storage

Avoid putting secrets in:

source code
GitHub repositories
README files
Dockerfiles
frontend JavaScript
logs
error messages
Enter fullscreen mode Exit fullscreen mode

Better options include:

environment variables
secret managers
container secrets
cloud provider secret stores
CI/CD secret stores
Enter fullscreen mode Exit fullscreen mode

38. Environment Variable Example

String clientId =
        System.getenv(
                "OAUTH_CLIENT_ID"
        );

String clientSecret =
        System.getenv(
                "OAUTH_CLIENT_SECRET"
        );
Enter fullscreen mode Exit fullscreen mode

Validate them:

if (clientId == null ||
    clientSecret == null) {

    throw new IllegalStateException(
            "OAuth credentials are missing"
    );
}
Enter fullscreen mode Exit fullscreen mode

39. Don't Print Secrets

This is dangerous:

System.out.println(
        "Token: " + token
);
Enter fullscreen mode Exit fullscreen mode

Also dangerous:

System.out.println(
        request.headers()
);
Enter fullscreen mode Exit fullscreen mode

because the headers may contain:

Authorization
Enter fullscreen mode Exit fullscreen mode

Instead, log only safe information:

System.out.println(
        request.method() +
        " " +
        request.uri()
);
Enter fullscreen mode Exit fullscreen mode

40. Redact Sensitive Headers

If you need to log headers, redact secrets.

Conceptually:

Authorization: Bearer ***
X-API-Key: ***
Enter fullscreen mode Exit fullscreen mode

Never log:

Authorization: Bearer actual-token-here
Enter fullscreen mode Exit fullscreen mode

41. Don't Put Tokens in URLs

Avoid:

https://api.example.com/users?token=SECRET
Enter fullscreen mode Exit fullscreen mode

URLs can appear in:

logs
browser history
proxy logs
analytics
monitoring tools
Enter fullscreen mode Exit fullscreen mode

Prefer headers:

Authorization: Bearer TOKEN
Enter fullscreen mode Exit fullscreen mode

42. HTTPS Is Mandatory

Authentication tokens should only be sent over HTTPS.

Avoid:

http://api.example.com
Enter fullscreen mode Exit fullscreen mode

Use:

https://api.example.com
Enter fullscreen mode Exit fullscreen mode

Without TLS, credentials may be exposed in transit.


43. Token Scope

OAuth tokens may have scopes.

For example:

users.read
users.write
orders.read
Enter fullscreen mode Exit fullscreen mode

A good security principle is:

grant only what is needed
Enter fullscreen mode Exit fullscreen mode

If your client only reads users, avoid asking for:

admin.full_access
Enter fullscreen mode Exit fullscreen mode

when:

users.read
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Better:

Get token
    ↓
cache it
    ↓
Call API
Call API
Call API
    ↓
token almost expired
    ↓
get new token
Enter fullscreen mode Exit fullscreen mode

This reduces unnecessary authorization-server traffic.


46. Thread Safety Matters

Suppose many threads call:

getToken()
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

That is wasteful.

Using:

synchronized
Enter fullscreen mode Exit fullscreen mode

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();
}
Enter fullscreen mode Exit fullscreen mode

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
        );
    }
}
Enter fullscreen mode Exit fullscreen mode

49. AccessToken Record

import java.time.Instant;

public record AccessToken(
        String value,
        Instant expiresAt
) {

    public boolean isExpired() {

        return Instant.now()
                .plusSeconds(30)
                .isAfter(
                        expiresAt
                );
    }
}
Enter fullscreen mode Exit fullscreen mode

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
) {
}
Enter fullscreen mode Exit fullscreen mode

51. TokenProvider

import java.io.IOException;

public interface TokenProvider {

    String getToken()
            throws IOException,
                   InterruptedException;

    void invalidate();
}
Enter fullscreen mode Exit fullscreen mode

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()
        );
    }
}
Enter fullscreen mode Exit fullscreen mode

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"
        );
Enter fullscreen mode Exit fullscreen mode

Create the token provider:

TokenProvider tokenProvider =
        new OAuthTokenProvider(
                "https://auth.example.com/oauth/token",
                clientId,
                clientSecret
        );
Enter fullscreen mode Exit fullscreen mode

Create the REST client:

RestClient client =
        new RestClient(
                tokenProvider
        );
Enter fullscreen mode Exit fullscreen mode

Call the API:

User user =
        client.get(
                "https://api.example.com/users/10",
                User.class
        );
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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
        );
    }
}
Enter fullscreen mode Exit fullscreen mode

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()
        );
    }
}
Enter fullscreen mode Exit fullscreen mode

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│
└─────────────────────┘
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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
    }
}
Enter fullscreen mode Exit fullscreen mode

Now the same REST client works for:

Public API
API key API
Bearer-token API
OAuth API
Enter fullscreen mode Exit fullscreen mode

59. Refresh Tokens

Some OAuth flows provide:

{
  "access_token": "...",
  "refresh_token": "...",
  "expires_in": 3600
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

60. Refresh Token Request

A request may look like:

grant_type=refresh_token
&refresh_token=...
&client_id=...
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

62. 401 vs 403

These two are commonly confused.

401 Unauthorized

Usually means:

authentication is missing or invalid
Enter fullscreen mode Exit fullscreen mode

Examples:

expired token
invalid token
missing credentials
Enter fullscreen mode Exit fullscreen mode

403 Forbidden

Usually means:

you are authenticated,
but you are not allowed to do this
Enter fullscreen mode Exit fullscreen mode

Example:

token has users.read
but endpoint requires users.delete
Enter fullscreen mode Exit fullscreen mode

A typical rule:

401
    → authentication problem

403
    → permission problem
Enter fullscreen mode Exit fullscreen mode

63. Don't Automatically Refresh on 403

Refreshing an access token usually does not fix missing permissions.

If the API returns:

403 Forbidden
Enter fullscreen mode Exit fullscreen mode

and the token lacks the required scope, getting another identical token will not help.

So:

401
    → maybe refresh once

403
    → usually fail
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Authentication should fit around that.

For example:

Send request
    ↓
401?
    ↓ yes
Refresh token once
    ↓
Retry request
    ↓
429 or 5xx?
    ↓
Apply retry/backoff rules
Enter fullscreen mode Exit fullscreen mode

But keep bounded retries.


66. Avoid Retry Loops Between Auth and Network Logic

Imagine:

401
    → refresh
    → 503
    → retry
    → 401
    → refresh
    → 503
    → retry
Enter fullscreen mode Exit fullscreen mode

Without limits, logic can become unpredictable.

Track:

authentication retries
network retries
Enter fullscreen mode Exit fullscreen mode

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?
Enter fullscreen mode Exit fullscreen mode

68. Common Mistakes

Mistake 1: Hardcoding secrets

String token =
        "secret-token";
Enter fullscreen mode Exit fullscreen mode

Mistake 2: Logging tokens

System.out.println(
        "Authorization: Bearer " +
        token
);
Enter fullscreen mode Exit fullscreen mode

Mistake 3: Putting tokens in URLs

/api/users?token=secret
Enter fullscreen mode Exit fullscreen mode

Mistake 4: Requesting a new token for every API call

token
request
token
request
token
request
Enter fullscreen mode Exit fullscreen mode

Mistake 5: Retrying 401 forever

401
refresh
401
refresh
401
refresh...
Enter fullscreen mode Exit fullscreen mode

Mistake 6: Treating decoded JWTs as verified JWTs

decoded ≠ trusted
Enter fullscreen mode Exit fullscreen mode

Mistake 7: Asking for excessive OAuth scopes

admin.*
Enter fullscreen mode Exit fullscreen mode

when:

users.read
Enter fullscreen mode Exit fullscreen mode

would be enough.


69. A Clean Architecture

A production-ready client might look like:

Application
    ↓
API-specific client
    ↓
RestClient
    ↓
AuthProvider
    ↓
TokenProvider
    ↓
Authorization Server
Enter fullscreen mode Exit fullscreen mode

And separately:

RestClient
    ↓
HttpClient
    ↓
External REST API
Enter fullscreen mode Exit fullscreen mode

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
)
Enter fullscreen mode Exit fullscreen mode

Bearer Token

.header(
    "Authorization",
    "Bearer " + token
)
Enter fullscreen mode Exit fullscreen mode

Environment Variable

String token =
        System.getenv(
                "ACCESS_TOKEN"
        );
Enter fullscreen mode Exit fullscreen mode

Client Credentials Grant

grant_type=client_credentials
Enter fullscreen mode Exit fullscreen mode

Token Expiration

Instant expiresAt =
        Instant.now()
                .plusSeconds(
                        expiresIn
                );
Enter fullscreen mode Exit fullscreen mode

Refresh Before Expiration

Instant.now()
        .plusSeconds(30)
        .isAfter(
                expiresAt
        );
Enter fullscreen mode Exit fullscreen mode

Handle 401

invalidate token
    ↓
get new token
    ↓
retry once
Enter fullscreen mode Exit fullscreen mode

403

usually do not refresh
Enter fullscreen mode Exit fullscreen mode

72. The Mental Model

The simplest authentication flow is:

Application
    ↓
Credentials
    ↓
Authorization server
    ↓
Access token
    ↓
REST client
    ↓
Authorization: Bearer TOKEN
    ↓
API
Enter fullscreen mode Exit fullscreen mode

When the token expires:

Token expired
    ↓
TokenProvider
    ↓
Request new token
    ↓
Cache token
    ↓
Continue API calls
Enter fullscreen mode Exit fullscreen mode

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
)
Enter fullscreen mode Exit fullscreen mode

But production systems quickly introduce more concerns:

token expiration
refresh
caching
thread safety
scope
secret storage
401 handling
logging
HTTPS
Enter fullscreen mode Exit fullscreen mode

The best approach is to keep these responsibilities separated.

A clean architecture might look like:

Application
    ↓
API Client
    ↓
RestClient
    ↓
AuthProvider
    ↓
TokenProvider
Enter fullscreen mode Exit fullscreen mode

That allows your application code to remain simple:

User user =
        userApi.getUser(10);
Enter fullscreen mode Exit fullscreen mode

while the lower layers handle:

OAuth
tokens
headers
refresh
authentication errors
HTTP
JSON
Enter fullscreen mode Exit fullscreen mode

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)