0
votes

I want to connect to OAuth 2.0 authorization type (with password grant_type) to get token with POST method, it's ok to test from Postman but i couldn't connect through PHP...
here's my information:
request url: 'http://example.com/core/connect/token'
ClientName: 'something1'
ClientId: 'something2'
Secret: 'something3'
UserName: 'something4'
Password: 'something5'
Scope: 'something6'

could you please just give me an example to get token and use?

i've already tested:

$base_url = 'https://example.com/oauth/token';  

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $base_url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
        'client_id'     => YOUR-CLIENT-ID,
        'client_secret' => YOUR-CLIENT-SECRET,
        'username'      => YOUR-USERNAME-OR-EMAIL,
        'password'      => YOUR-PASSWORD,
        'grant_type'    => 'password'
));

$data = curl_exec($ch);

$auth_string = json_decode($data, true);

and this

$api = "KEY GOES HERE";
$authurl = "http://example.com/core/connect/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 = array(
    '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;
echo $secret;
1

1 Answers

1
votes

The first call seems OK for the password grant type. The scope parameter should be optional. So...

Add this to your code to know the response from the server and therefore know the missing parameter or setting.

curl_setopt($ch, CURLOPT_VERBOSE, true);

Check the status code and a possible body with an error message.