# Connect using the OAuth1.0 signer library
source: https://developer.mastercard.com/straight-through-processing/documentation/tutorials-and-guides/connect-directly-to-the-api-with-oauth-tutorial/index.md

## Overview {#overview}

This tutorial explains the steps to integrate with Mastercard's OAuth 1.0 authentication and authorization flow.

### You will learn how to {#you-will-learn-how-to}

* Use Gradle to download the **OAuth1.0a** Java signer library for your project.
* Sign requests using our **OAuth1.0a** Java signer library.
* Call the STP service directly from a Spring application using OKHTTP3.

## Prerequisites {#prerequisites}

Before starting this tutorial, ensure that you have already completed the following tasks:

1. Supply the STP implementation team with the suppliers you want to use STP with.
2. Create your project and retrieve the required credentials by following the [Create a Sandbox project](https://developer.mastercard.com/straight-through-processing/documentation/tutorials-and-guides/create-sandbox-project-tutorial/index.md) tutorial.
3. Share your consumer key with the STP implementation team and receive confirmation that you have been onboarded to Sandbox.
4. Set up at least a basic Spring application project, such as the one from this [Tutorial](https://spring.io/guides/gs/spring-boot/#initial).

## Set up your Gradle dependencies {#set-up-your-gradle-dependencies}

We must add the [OAuth1.0 Java Signer Library](https://github.com/Mastercard/oauth1-signer-java#okhttp-3) to our project dependencies. For this tutorial, we will use [OKHTTP3](https://square.github.io/okhttp/) to send the requests; hence, you must add that as a dependency. Your `gradle.build` file should have entries as follows:

```gradle
dependencies {
  implementation "com.mastercard.developer:oauth1-signer:1.2.3"
  implementation "com.squareup.okhttp3:okhttp:3.14.2"
}
```

Make sure you rebuild your project to download the dependencies. You can do so by running the following command:

```terminal
./gradlew build
```

## Set up your configuration {#set-up-your-configuration}

You need to make sure everything is configured with your credentials so you can access the service.

Make sure to import the p12 file you downloaded when creating your project.

If you have followed the [Spring tutorial](https://spring.io/guides/gs/spring-boot/), then you can place it in the `/resources/static` folder as follows:
![Alt text](https://static.developer.mastercard.com/content/straight-through-processing/img/fileloc.png)

Next, we will create a Java file for holding our configuration. We create a simple final class to hold the four Strings for configuring our OAuth1.0 library. They are:

1. The path to the p12 file in your project structure.
2. The consumer key that you got when creating your project.
3. Your key alias and password retrieved when creating your project.


Note: We are only accessing the Stage environment here. When accessing the Production environment, insert the unique alias and password you created or received when moving to Production. Your Java class should look similar to this:

<br />

```java
public final class STPConfig {
    public static String P12_PATH = "./src/main/resources/static/<enter your file name here>.p12";
    public static String CONSUMER_KEY = "<enter your consumerkey here>";
    public static String KEY_ALIAS = "keyalias";
    public static String KEY_STORE_PASSWORD = "keystorepassword";
}
```

## Create your private signing key {#create-your-private-signing-key}

Create a Private Key using the `AuthenticationUtils` functionality of the OAuth1.0 signer library. Create a new class for handling this (we called ours STPClient.java) and add the following code:

```java
//Imports
import com.mastercard.developer.utils.AuthenticationUtils;
import java.security.PrivateKey;

//Place this code in the constructor 
try {
    PrivateKey signingKey = AuthenticationUtils.loadSigningKey(STPConfig.P12_PATH,
        STPConfig.KEY_ALIAS, STPConfig.KEY_STORE_PASSWORD);
} catch (UnrecoverableKeyException | NoSuchProviderException | KeyStoreException | CertificateException
        | NoSuchAlgorithmException | IOException e) {
        e.printStackTrace(); // Make sure you handle exceptions
}
```

## Sign an OKHTTP3 request {#sign-an-okhttp3-request}

We will use the signing key with the Mastercard OAuth1.0 OKHttpSigner. We first create a new OKHttpClient, and then we build our request. We sign and execute the request, listening for and printing out the response.

```java
//Imports
import com.mastercard.developer.signers.OkHttpSigner;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

//Place this code in a method where it makes sense for your application
OkHttpClient client= new OkHttpClient();

Request.Builder request = new Request.Builder() 
        .url("https://stage.api.mastercard.com/stp-api/v1/providers?Format=JSON")
        .get(); 

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

try (Response response = client.newCall(request.build()).execute()) {
    System.out.println(response.body().string());
}
```

In this example, we used the `GET` method on the `/providers` endpoint. You should expect a response similar to this:

```json

{
  "_embedded": {
    "providers": [
      {
        "name": "3-Delta",
        "customFields": [
          {
            "key": "MerchantID",
            "name": "MerchantID",
            "dataType": "ALPHA-25",
            "mandatory": false
          },
          {
            "key": "TerminalID",
            "name": "TerminalID",
            "dataType": "ALPHA-25",
            "mandatory": true
          },
          {
            "key": "LocationID",
            "name": "LocationID",
            "dataType": "NUMERIC-10",
            "mandatory": true
          }
        ],
        "_links": {
          "collection": {
            "href": "https://stage.api.mastercard.com/stp-api/v1/providers"
          },
          "self": {
            "href": "https://stage.api.mastercard.com/stp-api/v1/providers/2"
          }
        }
      },
      {
        "name": "TNS",
        "customFields": [
          {
            "key": "tns.merchant.id",
            "name": "Merchant ID",
            "dataType": "ALPHANUMERIC-25",
            "mandatory": true
          }
        ],
        "_links": {
          "collection": {
            "href": "https://stage.api.mastercard.com/stp-api/v1/providers"
          },
          "self": {
            "href": "https://stage.api.mastercard.com/stp-api/v1/providers/4"
          }
        }
      }
    ]
  },
  "_links": {
    "self": {
      "href": "https://stage.api.mastercard.com/stp-api/v1/providers"
    }
  }
}
```

Here is a POST example that shows what the request looks like when we need to send a payload:

```java
//Imports
import com.mastercard.developer.signers.OkHttpSigner;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

//Place this code in a method where it makes sense for your application
OkHttpClient client= new OkHttpClient();

String payload = "{\"name\": \"TEST_SUPPLIER\",\"clientRef\": \"12345\",\"active\": true,\"customFields\": [{\"key\": \"tns.merchant.id\",\"name\": \"Merchant ID\",\"value\": \"TESTSTPTEST01\"}],\"_links\": {\"provider\": {\"href\": \"https://stage.api.mastercard.com/stp-api/v1/providers/4\"}}}";

MediaType JSON = MediaType.parse("application/hal+json; charset=utf-8");
      
RequestBody body = RequestBody.create(JSON, payload);
            
Request.Builder request = new Request.Builder() 
    .url("https://stage.api.mastercard.com/stp-api/v1/suppliers?Format=JSON")
    .post(body); 

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

try (Response response = client.newCall(request.build()).execute()) {
     System.out.println(response.body().string());
}
```

The response looks like this:

```json
{
  "name": "TEST_SUPPLIER",
  "clientRef": "12345",
  "active": true,
  "customFields": [
    {
      "key": "tns.merchant.id",
      "name": "Merchant ID",
      "value": "M12345"
    }
  ],
  "_links": {
    "collection": {
      "href": "https://sandbox.api.mastercard.com/stp-api/v1/suppliers"
    },
    "provider": {
      "href": "https://sandbox.api.mastercard.com/stp-api/v1/providers/1"
    },
    "self": {
      "href": "https://sandbox.api.mastercard.com/stp-api/v1/suppliers/220242"
    }
  }
}
```

