Request OAuth token from BitBucket

2019-04-06 23:27发布

问题:

I've been trying to integrate BitBucket to my application for the past 4 hours to no avail.

While reading through BitBucket's RESTful API documentation, I noticed that you need to use OAuth — it's OK, I'm using J.R Conlin's OAuthSimple library, which if fine by me (I tried oauth-php but it was kinda complicated — I didn't need all of those options for such a small integration).

For what I understand, the first step to authenticate with OAuth is to request a new token via POST. When providing the necessary parameters, you should get a response from BitBucket, like this:

oauth_token=Z6eEdO8lOmk394WozF9oJyuAv899l4llqo7hhlSLik&oauth_token_secret=Jd79W4OQfb2oJTV0vzGzeXftVAwglnEJ9lumzYcl&oauth_callback_confirmed=true

To do that, I'm using cURL and OAuthSimple:

$key    = 'key_provided_by_bitbucket';
$secret = 'key_provided_by_bitbucket';
$path   = 'https://api.bitbucket.org/1.0/oauth/request_token';

$params = array(
    'oauth_consumer_key'        => $key,
    'oauth_nonce'               => base_convert(mt_rand(10000, 90000), 10, 32) . 'a',
    'oauth_signature'           => 'HMAC-SHA1',
    'oauth_signature_method'    => 'HMAC-SHA1',
    'oauth_timestamp'           => time(),
    'oauth_callback'            => base_url('dashboard'),
    'oauth_version'             => '1.0a'
);

$oauth  = new OAuthSimple($key, $secret);
$result = $oauth->sign(array(
    'action'        => 'POST',
    'path'          => $path,
    'parameters'    => $params
));

// load resulting url into a string
$ch = curl_init($result['signed_url']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$r = curl_exec($ch);
curl_close($ch);

The thing is that, when I send my request, one of two things happen:

  1. If I send it like posted here, I will get a 401 error (I can see that via curl_getinfo($ch))
  2. If I set curl_setopt($ch, CURLOPT_POST, 1), I get a 400 Bad request

The resulting string (stored in $r) is an empty string. The signed_url is a correctly formed URL AFAIK, which is something like this:

https://api.bitbucket.org/1.0/oauth/request_token?oauth_callback=http%3A%2F%2Flocalhost%2Fidv&oauth_consumer_key=key_provided_by_bitbucket&oauth_nonce=b47a&oauth_signature=3A1R%2FoKxTqh6Q23poaS%2BVNzhwpE%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1347167282&oauth_version=1.0a

If I enter manually that address into my address bar in a browser, I'll get an Authentication Dialog to the BitBucket API, port 443. I can't login with my credentials, though. Then it will just keep saying "Could not verify OAuth request."

I don't know what I'm doing wrong, since it's my first time using OAuth.

Any help's appreciated!

回答1:

The problem is that Curl will verify the SSL certificate.

To solve the problem you can tell Curl to ignore the verification of the SSL certificates:

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);