0

I am trying to get a token to use the Microsoft Graph API (https://learn.microsoft.com/en-us/graph/auth-v2-user?context=graph%2Fapi%2F1.0&view=graph-rest-1.0) via Curl. I have set up a simple Php file with this function:

function getToken() {
echo "start gettoken";
var_dump(extension_loaded('curl'));
$jsonStr = http_build_query(Array(
    "client_id" => "***",
    "scope" => "https://graph.microsoft.com/.default",
    "client_secret" => "***",
    "grant_type" => "client_credentials"
));
$headers = Array("Content-Type: application/x-www-form-urlencoded", "Content-Length: " . strlen($jsonStr));

$ch = curl_init("https://login.microsoftonline.com/***.onmicrosoft.com/oauth2/v2.0/token");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$token = curl_exec($ch);
echo "test after curl";

return $token;

curl_error($ch);

 }

However, what I want to know is why the curl request is not working. Also the echo after the curl codeblock is not being executed, while 'start gettoken' is. PHP_curl is enabled in my WAMP. Why is this?

Y_Lakdime
  • 825
  • 2
  • 15
  • 33

2 Answers2

0

Are you sure CURL is enabled because that code you have posted is ok and giving echo response before and after curl execution.

0

you're sending the token request in a JSON-format, and then you're lying to the server saying it's application/x-www-form-urlencoded-encoded when it's actually application/json-encoded! since these 2 formats are completely incompatible, the server fails to parse it, and... ideally it should have responded HTTP 400 bad request (because your request can't be parsed as x-www-form-urlencoded)

anyhow, to actually send it in the application/x-www-form-urlencoded-format, replace json_encode() with http_build_query()

also get rid of the "Content-Length:"-header, it's easy to mess up (aka error-prone) if you're doing it manually (and indeed, you messed it up! there's supposed to be a space between the : and the number, you didn't add the space, but the usual error is supplying the wrong length), but if you don't do it manually, then curl will create the header for you automatically, which is not error-prone.

hanshenrik
  • 19,904
  • 4
  • 43
  • 89
  • Thank you for your reply, in the docs (https://learn.microsoft.com/en-us/graph/auth-v2-user?context=graph%2Fapi%2F1.0&view=graph-rest-1.0) it says that you should put application/x-www-form-urlencoded :). Btw, I applied your suggestions but I still dont get back the token at 'echo $token' :( – Y_Lakdime Oct 08 '19 at 17:14
  • @user3660293 show me the code where you `applied my suggestions` – hanshenrik Oct 08 '19 at 20:13
  • instead of removing the Content-Length header, ive added the space. because It expects an array – Y_Lakdime Oct 09 '19 at 07:59