JAVA - How to build a client for OAuth 1.0 REST API with signature method as HMAC-SHA256?

1.8k views Asked by At

I'm able to consume APIs (OAuth 1.0 Authorization & signature method as HMAC-SHA256) in POSTMAN, but not working JAVA (maven project). Generated code from POSTMAN with OkHttp & Unirest libraries, both are not working. They give the following error.

403 Forbidden

I understand error is related to invalid authentication parameters. But not able to figure out what needs to be changed. Because same keys are working in Postman

OkHttp JAVA Code

OkHttpClient client = new OkHttpClient().newBuilder().build();
MediaType mediaType = MediaType.parse("application/json");
String url = "https://www.example.com?script=508&deploy=1";
String JSONpayload = "{}";
RequestBody body = RequestBody.create(mediaType, JSONpayload);
Request request = new Request.Builder()
  .url(url)
  .method("POST", body)
  .addHeader("Content-Type", "application/json")
  .addHeader("Authorization", "OAuth realm=\"1111222_SB1\",oauth_consumer_key=\"xxxxxxxxx\",oauth_token=\"xxxxxxxx\",oauth_signature_method=\"HMAC-SHA256\",oauth_timestamp=\"1628747273\",oauth_nonce=\"xxxxxx\",oauth_version=\"1.0\",oauth_signature=\"xxxxxxxxxxx\"")
  .addHeader("Cookie", "NS_ROUTING_VERSION=LAGGING")
  .build();
Response response = client.newCall(request).execute();

Unirest JAVA Code

Unirest.setTimeouts(0, 0);
String url = "https://www.example.com?script=508&deploy=1";
String JSONpayload = "{}";
HttpResponse<String> response = Unirest.post(url)
  .header("Content-Type", "application/json")
  .header("Authorization", "OAuth realm=\"1114415_SB1\",oauth_consumer_key=\"xxxxxxxxxx\",oauth_token=\"xxxxxxxxxxx\",oauth_signature_method=\"HMAC-SHA256\",oauth_timestamp=\"1628747273\",oauth_nonce=\"xxxxxxxx\",oauth_version=\"1.0\",oauth_signature=\"xxxxxxxx\"")
  .header("Cookie", "NS_ROUTING_VERSION=LAGGING")
  .body(JSONpayload).asString();

Any kind of help is appreciated. Thanks in Advance.

0

There are 0 answers