Can't get user token : "cannot retrieve client credentials" (PHP / cURL)

Hi,

I’m trying to authenticate on the REST API with PHP and cURL on a friend’s instance :

$curl = curl_init('https://tube.example.com/api/v1/users/token');

curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

curl_setopt($curl, CURLOPT_POST, true);

$fields = json_encode(array(
  'client_id' => 'xxxxxxxxxxxxxxx',
  'client_secret' => 'yyyyyyyyyyyyy',
  'grant_type' => 'password',
  'response_type' => 'code',
  'username' => 'myuser',
  'password' => 'mypw'));

curl_setopt($curl, CURLOPT_POSTFIELDS, $fields);

$response = curl_exec($curl);

But Peertube returns an error :

{"error":"Invalid client: cannot retrieve client credentials","code":"invalid_client"}

What’s wrong ? The same credentials I use in the terminal as explained at https://docs.joinpeertube.org/#/api-rest-getting-started?id=get-user-token, do return a token as expected.

Thanks !

Try without json_encode, and set "Content-Type: application/x-www-form-urlencoded" has header

1 « J'aime »

Thanks @Chocobozzz !

Removed json_encode() and added curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));.

No luck, same error.

Try curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($fields));

Thanks @Chocobozzz, that’s it.
So to make it clear, here is the code, corrected :

$curl = curl_init('https://tube.example.com/api/v1/users/token');

curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

curl_setopt($curl, CURLOPT_POST, true);

$fields = array(
  'client_id' => 'xxxxxxxxxxxxxxx',
  'client_secret' => 'yyyyyyyyyyyyy',
  'grant_type' => 'password',
  'response_type' => 'code',
  'username' => 'myuser',
  'password' => 'mypw');

curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($fields));

$response = curl_exec($curl);

Note that "Content-Type: application/x-www-form-urlencoded" as a header is not necessary.

1 « J'aime »