OAuth2 Client Java
Overview
Easily access Mastercard APIs with OAuth 2.0 and FAPI 2.0. This zero-dependency library handles authentication for you.
For more information, see Using OAuth 2.0 to Access Mastercard APIs.
Requirements
License
This project is licensed under the Apache License 2.0.
Java
To use this project, you will need Java 17 or higher. Java 17 is an LTS release and has become the practical baseline for modern Java frameworks (for example Spring Boot 3).
Zero-Dependency
The code is compiled using "provided" dependencies to keep the artifact small, prevent version conflicts, and let you choose which HTTP client and JSON provider to use at runtime.
The modular structure lets you import only what you need. For example, when using OkHttp and classes from the okhttp3 package, only the OkHttp library needs to be on the classpath.
At least one JSON library (Jackson, Gson, or org.json) must be available on the classpath for JSON processing.
To verify that runtime dependencies are minimal, run cd library && mvn dependency:tree -Dscope=runtime. Expected output:
[INFO] --- dependency:3.7.0:tree (default-cli) @ oauth2-client-java ---
[INFO] com.mastercard.developer:oauth2-client-java:jar:{version}
[INFO] \- org.slf4j:slf4j-api:jar:{version}:compile
Documentation
A Javadoc site is available on javadoc.io. Additionally, you can use DeepWiki and Context7 to explore the library further.
Usage
Maven dependency
To start, add the following dependency to your project:
Maven POM
<dependency>
<groupId>com.mastercard.developer</groupId>
<artifactId>oauth2-client-java</artifactId>
<version>${oauth2-client-version}</version>
</dependency>
Gradle Build File
dependencies {
implementation "com.mastercard.developer:oauth2-client-java:$oauth2ClientVersion"
}
Configuration
The OAuth2Config object contains your client credentials, DPoP key configuration, token endpoint, and other settings for OAuth 2.0 authentication.
Here's how to build an instance:
PrivateKey clientKey = KeyLoader.loadPrivateKey(Paths.get("path/to/client-private-key.pem"));
KeyPair dpopKeyPair = KeyLoader.loadKeyPair(Paths.get("path/to/dpop-private-key.json")); // Or KeyGenerator.generateEcKeyPair("secp256r1");
OAuth2Config config = OAuth2Config.builder()
.securityProfile(SecurityProfile.FAPI2SP_PRIVATE_KEY_DPOP)
.clientId("ZvT0sklPsqzTNgKJIiex5_wppXz0Tj2wl33LUZtXmCQH8dry")
.tokenEndpoint(new URL("https://sandbox.api.mastercard.com/oauth/token"))
.issuer(new URL("https://sandbox.api.mastercard.com"))
.clientKey(clientKey)
.kid("302449525fad5309874b16298f3cbaaf0000000000000000")
.accessTokenStore(new InMemoryAccessTokenStore())
.scopeResolver(new StaticScopeResolver(Set.of("service:scope1", "service:scope2")))
.dpopKeyProvider(new StaticDPoPKeyProvider(dpopKeyPair))
.clockSkewTolerance(Duration.ofSeconds(10))
.build();
Notes:
Low-Level API
The OAuth2Handler class provides public static methods that handle client assertion generation, DPoP proof creation, access token request creation and access token response parsing.
Supported HTTP Clients
For a higher-level experience, use the provided HTTP-client related classes (interceptors, filters, or client wrappers), automatically invoking the OAuth2Handler logic under the hood.
Pick the HTTP client that works best for your application. All implementations provide the same functionality.
OkHttp
| Supported versions |
Status |
| 4.x, 5.x |
|
The OAuth2Interceptor is an OkHttp interceptor that adds access tokens and DPoP proofs to outgoing requests. Register it with OkHttpClient.Builder.addInterceptor().
OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(new OAuth2Interceptor(config, baseClient.newBuilder()))
.build();
Call call = httpClient.newCall(request);
Response response = call.execute();
OpenAPI Generator: okhttp-gson
OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(new OAuth2Interceptor(config, baseClient.newBuilder()))
.build();
var client = new ApiClient(httpClient);
client.setBasePath(baseUri);
var api = new ResourcesApi(client);
Resource resource = api.createResource(new Resource());
Java HTTP Client
| Supported versions |
Status |
| Java 17 to 25 |
|
OAuth2HttpClient extends HttpClient and provides a builder that extends HttpClient.Builder. Use it as a drop-in replacement for the standard Java HTTP client.
HttpClient httpClient = OAuth2HttpClient.newBuilder(config, baseBuilder).build();
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
OpenAPI Generator: native
var client = new ApiClient();
client.setHttpClientBuilder(OAuth2HttpClient.newBuilder(config, baseBuilder));
client.updateBaseUri(baseUri);
var api = new ResourcesApi(client);
Resource resource = api.createResource(new Resource());
Apache HttpClient
| Supported versions |
Status |
| 5.4.x, 5.5.x, 5.6.x |
|
OAuth2HttpClient extends CloseableHttpClient. It wraps request execution to add access tokens and DPoP proofs before sending requests.
CloseableHttpClient httpClient = new OAuth2HttpClient(config);
ClassicHttpResponse httpResponse = httpClient.execute(request, response -> handleResponse(response));
OpenAPI Generator: apache-httpclient
CloseableHttpClient httpClient = new OAuth2HttpClient(config);
var client = new ApiClient(httpClient);
client.setBasePath(baseUri);
var api = new ResourcesApi(client);
Resource resource = api.createResource(new Resource());
OpenFeign
| Supported versions |
Status |
| 11.1+, 12.x, 13.x |
|
OAuth2Client implements Feign's Client interface. It intercepts requests to add access tokens and DPoP proofs. It can be passed to Feign.Builder.client().
Client feignClient = new OAuth2Client(config);
HttpResponse<String> response = feignClient.execute(request, new Request.Options());
OpenAPI Generator: feign
Client feignClient = new OAuth2Client(config);
var client = new ApiClient();
client.getFeignBuilder().client(feignClient);
client.setBasePath(baseUri);
ResourcesApi api = client.buildClient(ResourcesApi.class);
Resource resource = api.createResource(new Resource());
Spring WebClient
| Supported versions |
Status |
spring-webflux 6.0.x, 6.1.x, 6.2.x, 7.0.x |
|
OAuth2Filter implements ExchangeFilterFunction. It intercepts requests to add access tokens and DPoP proofs. Register it with WebClient.Builder.filter().
var filter = new OAuth2Filter(config);
WebClient webClient = WebClient.builder().filter(filter).build();
ResponseSpec response = webClient.get().uri(uri).retrieve();
OpenAPI Generator: webclient
var filter = new OAuth2Filter(config);
WebClient webClient = WebClient.builder().filter(filter).build();
var client = new ApiClient(webClient);
client.setBasePath(baseUri);
var api = new ResourcesApi(client);
Resource resource = api.createResource(new Resource());
Spring RestClient
| Supported versions |
Status |
spring-web 6.2.x, 7.0.x |
|
OAuth2ClientHttpRequestInterceptor implements ClientHttpRequestInterceptor. It intercepts requests to add access tokens and DPoP proofs. Register it with RestClient.Builder.requestInterceptor().
var interceptor = new OAuth2ClientHttpRequestInterceptor(config);
RestClient restClient = baseBuilder.requestInterceptor(interceptor).build();
ResponseSpec response = restClient.get().uri(uri).retrieve();
OpenAPI Generator: restclient
var interceptor = new OAuth2ClientHttpRequestInterceptor(config);
RestClient restClient = baseBuilder.requestInterceptor(interceptor).build();
var client = new ApiClient(restClient);
client.setBasePath(baseUri);
var api = new ResourcesApi(client);
Resource resource = api.createResource(new Resource());
Test Strategy
Each supported HTTP client has two types of tests:
- Direct HTTP client usage: tests that exercise the HTTP client directly
- OpenAPI Generator integration: tests that validate compatibility with API clients generated at build time (see
test-clients module)
Both types run against a real service and fake servers.
Real Service
Local Development
Running integration tests against a real Mastercard API requires API details and credentials. For that:
- Run:
cp.env.example.env
- Update
.env with the required values
GitHub Actions
This repository is configured with the following secrets GitHub Actions automatically uses when running workflows:
Fake Servers
Fake servers use WireMock to simulate OAuth 2.0 authorization and protected API resource servers.
See: FakeAuthorizationServer, FakeResourceServer.
Extension Points
This library is small by design and built to be extended. Common extension points are listed below.
- Implement
ScopeResolver to control which scopes are requested for a given URL or endpoint
- Use
StaticScopeResolver for simple fixed-scope cases
- Implement
DPoPKeyProvider to supply keys for DPoP proofs
- Use
StaticDPoPKeyProvider for a single, static key
- For short-lived DPoP keys, implement a provider that returns different keys over time
- Implement
AccessTokenStore to control how access tokens are cached and retrieved
- Use
InMemoryAccessTokenStore