How to generate HMAC-SHA1 signature to use with WP REST API and OAuth1

I’m trying to publish a post using WP REST API.
I was able to authenticate using OAuth1 using the PAW http client.
I was able to publish a post to the site as well (again using PAW).

PAW generated PHP code for me to use on my site. I created test.php and inserted the code there. Tried opening the page in browser. It was not getting authenticated. It said, (the first time) that the signature is invalid, and one other time, that the timestamp is invalid, and one other time, the noncce is invalid.

I checked in PAW – and found that, at each new run, PAW generates, a unique nonce, timestamp, and also HMAC-SHA1 signature – but the code which I’ve code is with the same nonce, timestamp, and HMAC-SHA1 signature – at each run. I think I need to find a way to automatically generate unique nonce, timestamp and signature.

Can anyone help me?

Below is the code:

<?php

// Get cURL resource
$ch = curl_init();

// Set url
curl_setopt($ch, CURLOPT_URL, 'http://sitename.com/wp-json/wp/v2/posts');

// Set method
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');

// Set options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

// Set headers
curl_setopt($ch, CURLOPT_HTTPHEADER, [
  "Authorization: OAuth oauth_consumer_key=\"zfksKSt8m7Bk\", oauth_nonce=\"dWXo8bGuKTMEqbmLf8cwqcWjfjDyqwKh\", oauth_signature=\"%2BOy0fDsKilNymYOOZRqjJN5q3tg%3D\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"1468900106\", oauth_token=\"IG6x6jIjboVhmyzFtjzn1fGT\", oauth_version=\"1.0\"",
  "Content-Type: application/json; charset=utf-8",
 ]
);
// Create body
$json_array = [
            "title" => "This is going to be a newww posttt"
        ];
$body = json_encode($json_array);

// Set body
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);

// Send the request & save response to $resp
$resp = curl_exec($ch);

if(!$resp) {
  die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
} else {
  echo "Response HTTP Status Code : " . curl_getinfo($ch, CURLINFO_HTTP_CODE);
  echo "\nResponse HTTP Body : " . $resp;
}

// Close request to clear up some resources
curl_close($ch);

1 Answer
1

I have same problem but for auto generate time and nonce you can do this:

<?php
$nonce = md5(mt_rand());
// Set headers
curl_setopt($ch, CURLOPT_HTTPHEADER, ['
    Authorization: OAuth oauth_consumer_key="zfksKSt8m7Bk",
    oauth_nonce=".$nonce.",
    oauth_signature="%2BOy0fDsKilNymYOOZRqjJN5q3tg%3D",
    oauth_signature_method="HMAC-SHA1",
    oauth_timestamp='.time().',
    oauth_token="IG6x6jIjboVhmyzFtjzn1fGT",
    oauth_version="1.0"
    ',
    'Content-Type: application/json; charset=utf-8',
]
);

I’m study for generate signature. I think It Can Be Useful To generate the signature using something like

$signature = hash_hmac( 'sha1', $base_string, $key );

Leave a Comment