handkock
handkock

Reputation: 1077

Bearer Authorization denied in api using cURL

I want to make a simple post request to an API server. I know, there are lot of information about cURL in web, but I can't figure out, why am I getting:

[message] => Authorization has been denied for this request.

So the API uses standard bearer token(in the header Authorization: Bearer {tokenID})

my php code:

$body = array(
        "id" => $uuid,
        "userAccountId" => $userAccountId,
        "email" => $email,
        "first_name" => $first_name,
        "last_name" => $last_name,
        "phone" => $phone,
      );

      $ch = curl_init();
      curl_setopt($ch, CURLOPT_HTTPHEADER, http_build_query(array(
        'Authorization' => $token,
      )));
      curl_setopt($ch, CURLOPT_URL, $myurl);
      curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($body));
      curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
      $result = curl_exec($ch);
      curl_close($ch);
      $result = json_decode($result);

The most interesting and weird thing is, that, when I send a Post request to the same url with the same body and the same header(same token) using postman, it works, however it doesn't work with php cURL. Also I tried with https://www.codepunker.com/tools/http-requests and got the same Authorization error. Has anyone any ide what could it be ?

Upvotes: 3

Views: 9123

Answers (1)

handkock
handkock

Reputation: 1077

I found the issue: I should have used json_encode($body) instead http_build_query($body) and the header in the following way:

      curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Authorization: Bearer .....',
        'accept: application/json',
        'content-type: application/json',
      ));

Upvotes: 2

Related Questions