Search code examples
phpoauth-2.0

OAuth2 Token PHP


I need to connect with an API that is using oAuth2. I have never used oAuth2 before and im not really sure how to. The provider is giving this information:

Obtaining an access token is done by sending an HTTP POST request to the above endpoint. The request should contain the following headers:

Authorization: Basic [client_id]:[client_secret]
Content-Type: application/x-www-form-urlencoded

Where [client_id] and [client_secret] should be replaced with your information. The composed [client_id]:[client_secret] string should be base64 encoded.

The header should look something like this:

Authorization: Basic bXlfY2xpZW50X2lkOnBFUnkyTGhLYko0U2FkY3ZLcklpQW5xWnprakg5bm9STUc3aUxZcWl2MA==

Finally, you need the following request body:

grant_type=password&scope=read write&username=[username]&password=[password]

Where [username] and [password] should be replaced with your credentials. If you are accessing the API with an API-key you should replace both [username] and [password] with the API-key obtained above.

If your request was composed correctly, and your credentials were correct, the server will return an access_token in JSON format for you to use:

{
    "access_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9(...)",
    "token_type":"Bearer",
    "expires_in":3600,
    "refresh_token":null
}

What I tried is the following, but it returns an invalid request message:

    $api = "KEY GOES HERE";
$authurl = "https://url.com/oauth/token";

$client_id = "ID GOES HERE";
$client_secret = "SECRET GOES HERE";

// Creating base 64 encoded authkey
$Auth_Key = $client_id.":".$client_secret;
$encoded_Auth_Key=base64_encode($Auth_Key);

$headers = array();
$headers['Authorization'] = "Basic ".$encoded_Auth_Key;
$headers['Content-Type'] = "application/x-www-form-urlencoded";

$data = "grant_type=password&scope=read write&username=".$api."&password=".$api."";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $authurl);
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);

$auth = curl_exec( $ch );

if ( curl_errno( $ch ) ){
    echo 'Error: ' . curl_error( $ch );
}
curl_close($ch);

$secret = json_decode($auth);
$access_key = $secret->access_token;

Solution

  • All your code looks good except the POST field data. The problem is that your query string is already encoded. When you call curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));, then it is encoded again.

    I recommend you to set the variable $data as an array:

    $data = array(
        'grant_type' => 'password',
        'scope'      => 'read write',
        'username'   => $api,
        'password'   => $api,
    );
    

    The query string will be correctly encoded when http_build_query is called.