Skip to content

Latest commit

 

History

History
286 lines (240 loc) · 11.8 KB

README.md

File metadata and controls

286 lines (240 loc) · 11.8 KB

oauth1-signer-java

Table of Contents

Overview

Zero dependency library for generating a Mastercard API compliant OAuth signature.

Compatibility

Java 11+

References

Versioning and Deprecation Policy

Usage

Prerequisites

Before using this library, you will need to set up a project in the Mastercard Developers Portal.

As part of this set up, you'll receive credentials for your app:

  • A consumer key (displayed on the Mastercard Developer Portal)
  • A private request signing key (matching the public certificate displayed on the Mastercard Developer Portal)

Adding the Library to Your Project

Maven

<dependency>
    <groupId>com.mastercard.developer</groupId>
    <artifactId>oauth1-signer</artifactId>
    <version>${oauth1-signer-version}</version>
</dependency>

Gradle

dependencies {
    implementation "com.mastercard.developer:oauth1-signer:$oauth1SignerVersion"
}

Other Dependency Managers

See: https://search.maven.org/artifact/com.mastercard.developer/oauth1-signer

Loading the Signing Key

A PrivateKey key object can be created by calling the AuthenticationUtils.loadSigningKey method:

PrivateKey signingKey = AuthenticationUtils.loadSigningKey(
                                    "<insert PKCS#12 key file path>", 
                                    "<insert key alias>", 
                                    "<insert key password>");

Creating the OAuth Authorization Header

The method that does all the heavy lifting is OAuth.getAuthorizationHeader. You can call into it directly and as long as you provide the correct parameters, it will return a string that you can add into your request's Authorization header.

String consumerKey = "<insert consumer key>";
URI uri = URI.create("https://sandbox.api.mastercard.com/service");
String method = "POST";
String payload = "Hello world!";
Charset charset = StandardCharsets.UTF_8;
String authHeader = OAuth.getAuthorizationHeader(uri, method, payload, charset, consumerKey, signingKey);

Signing HTTP Client Request Objects

Alternatively, you can use helper classes for some of the commonly used HTTP clients.

These classes, provided in the com.mastercard.developer.signers package, will modify the provided request object in-place and will add the correct Authorization header. Once instantiated with a consumer key and private key, these objects can be reused.

Usage briefly described below, but you can also refer to the test package for examples.

Java HttpsURLConnection

Charset charset = StandardCharsets.UTF_8;
URL url = new URL("https://sandbox.api.mastercard.com/service");
String payload = "{\"foo\":\"bar\"}";

HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json; charset=" + charset.name());

HttpsUrlConnectionSigner signer = new HttpsUrlConnectionSigner(charset, consumerKey, signingKey);
signer.sign(con, payload);

Apache HTTP Client 4

String payload = "{\"foo\":\"bar\"}";

HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost("https://sandbox.api.mastercard.com/service");
httpPost.setEntity(new StringEntity(payload, ContentType.APPLICATION_JSON));

ApacheHttpClient4Signer signer = new ApacheHttpClient4Signer(consumerKey, signingKey);
signer.sign(httpPost);

OkHttp 3

MediaType JSON = MediaType.parse("application/json; charset=utf-8");
String payload = "{\"foo\":\"bar\"}";

OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(JSON, payload);
Request.Builder request = new Request.Builder()
        .url("https://sandbox.api.mastercard.com/service")
        .post(body);

OkHttpSigner signer = new OkHttpSigner(consumerKey, signingKey);
signer.sign(request);

Integrating with OpenAPI Generator API Client Libraries

OpenAPI Generator generates API client libraries from OpenAPI Specs. It provides generators and library templates for supporting multiple languages and frameworks.

The com.mastercard.developer.interceptors package will provide you with some request interceptor classes you can use when configuring your API client. These classes will take care of adding the correct Authorization header before sending the request.

Library options currently supported for the java generator:

See also:

okhttp-gson

OpenAPI Generator Plugin Configuration
<configuration>
    <inputSpec>${project.basedir}/src/main/resources/openapi-spec.yaml</inputSpec>
    <generatorName>java</generatorName>
    <library>okhttp-gson</library>
    <!-- ... -->
</configuration>
Usage of the OkHttp2OAuth1Interceptor (OpenAPI Generator 3.3.x)
ApiClient client = new ApiClient();
client.setBasePath("https://sandbox.api.mastercard.com");
List<Interceptor> interceptors = client.getHttpClient().interceptors();
interceptors.add(new OkHttp2OAuth1Interceptor(consumerKey, signingKey));
ServiceApi serviceApi = new ServiceApi(client);
// ...
Usage of the OkHttpOAuth1Interceptor (OpenAPI Generator 4+)
ApiClient client = new ApiClient();
client.setBasePath("https://sandbox.api.mastercard.com");
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("https://proxy-url.com", 8866)); // Optional Proxy Configuration
client.setHttpClient(
    client.getHttpClient()
        .newBuilder()
        .proxy(proxy) // Optional proxy
        .addInterceptor(new OkHttpOAuth1Interceptor(consumerKey, signingKey))
        .build()
);
ServiceApi serviceApi = new ServiceApi(client);
// ...

feign

OpenAPI Generator Plugin Configuration
<configuration>
    <inputSpec>${project.basedir}/src/main/resources/openapi-spec.yaml</inputSpec>
    <generatorName>java</generatorName>
    <library>feign</library>
    <!-- ... -->
</configuration>
Usage of the OpenFeignOAuth1Interceptor
ApiClient client = new ApiClient();
client.setBasePath("https://sandbox.api.mastercard.com");
Feign.Builder feignBuilder = client.getFeignBuilder();
ArrayList<RequestInterceptor> interceptors = new ArrayList<>();
interceptors.add(new OpenFeignOAuth1Interceptor(consumerKey, signingKey, client.getBasePath()));
feignBuilder.requestInterceptors(interceptors);
ServiceApi serviceApi = client.buildClient(ServiceApi.class);
// ...

retrofit

OpenAPI Generator Plugin Configuration
<configuration>
    <inputSpec>${project.basedir}/src/main/resources/openapi-spec.yaml</inputSpec>
    <generatorName>java</generatorName>
    <library>retrofit</library>
    <!-- ... -->
</configuration>
Usage of the OkHttp2OAuth1Interceptor
ApiClient client = new ApiClient();
RestAdapter.Builder adapterBuilder = client.getAdapterBuilder();
adapterBuilder.setEndpoint("https://sandbox.api.mastercard.com"); 
List<Interceptor> interceptors = client.getOkClient().interceptors();
interceptors.add(new OkHttp2OAuth1Interceptor(consumerKey, signingKey));
ServiceApi serviceApi = client.createService(ServiceApi.class);
// ...

retrofit2

OpenAPI Generator Plugin Configuration
<configuration>
    <inputSpec>${project.basedir}/src/main/resources/openapi-spec.yaml</inputSpec>
    <generatorName>java</generatorName>
    <library>retrofit2</library>
    <!-- ... -->
</configuration>
Usage of the OkHttpOAuth1Interceptor
ApiClient client = new ApiClient();
Retrofit.Builder adapterBuilder = client.getAdapterBuilder();
adapterBuilder.baseUrl("https://sandbox.api.mastercard.com"); 
OkHttpClient.Builder okBuilder = client.getOkBuilder();
okBuilder.addInterceptor(new OkHttpOAuth1Interceptor(consumerKey, signingKey));
ServiceApi serviceApi = client.createService(ServiceApi.class);
// ...

google-api-client

OpenAPI Generator Plugin Configuration
<configuration>
    <inputSpec>${project.basedir}/src/main/resources/openapi-spec.yaml</inputSpec>
    <generatorName>java</generatorName>
    <library>google-api-client</library>
    <!-- ... -->
</configuration>
Usage of the HttpExecuteOAuth1Interceptor
HttpRequestInitializer initializer = new HttpRequestInitializer() {
    @Override
    public void initialize(HttpRequest request) {
        request.setInterceptor(new HttpExecuteOAuth1Interceptor(consumerKey, signingKey));
    }
};
ApiClient client = new ApiClient("https://sandbox.api.mastercard.com", null, initializer, null);
ServiceApi serviceApi = client.serviceApi();
// ...