question

Upvotes
Accepted
1 1 1 4

Sample oauth token php code

I'm just getting started and using PHP to call the API. I'm trying to get an OAuth token but the server response is empty including no error message. I've also tried using the Chroma Advanced REST Client and I get the same lack of response. Do I need separate permissions? Any assistance would be welcomed.

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,"https://{instance}/app/oauth/token");

curl_setopt($ch, CURLOPT_POST, 1);

curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json' ));

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

curl_setopt($ch, CURLOPT_USERPWD, "{user}:{pass}");

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);

$response = curl_exec($ch);

$curl_errno = curl_errno($ch);

curl_close($ch);

data-fusionoauth
icon clock
10 |1500

Up to 2 attachments (including images) can be used with a maximum of 5.0 MiB each and 10.0 MiB total.

1 Answer

Upvotes
Accepted
1.2k 6 10 8

It looks like you're using basic auth instead of posting the credentials in the request's body. As a reference Postman generates the following code for php.

<?php
$curl = curl_init();
curl_setopt_array($curl, array(
  CURLOPT_URL => "https://{instance}/app/oauth/token",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "{\"username\":\"yourusername\", \"yourpassword\":\"{pass}\"}",
  CURLOPT_HTTPHEADER => array(
    "cache-control: no-cache",
    "content-type: application/json"
  ),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}
icon clock
10 |1500

Up to 2 attachments (including images) can be used with a maximum of 5.0 MiB each and 10.0 MiB total.

Click below to post an Idea Post Idea