question

testlast-1664 avatar image
0 Votes"
testlast-1664 asked testlast-1664 commented

Token is not vaild while using the graph api

Helllo,

I'm using "Microsoft\Graph\Graph" package for upload the files over one drive. Token is not valid while trying to use the below code.

------------------------------------------------ Get Token Function --------------------------------------------------------
$body = "grant_type=client_credentials"
."&client_id=XXXXXXXXX"
."&scope=https://graph.microsoft.com/.default"
."&client_secret=XXXXXXXXX";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://login.microsoftonline.com/consumers/oauth2/v2.0/token');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_FAILONERROR, 0);
// curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // turns off SSL check,
// curl_setopt($ch, CURLOPT_PROXY, "127.0.0.1:8888"); // need for fiddler + auth
curl_setopt($ch, CURLOPT_HTTPHEADER, array('application/x-www-form-urlencoded', 'Content-Length: ' . strlen($body)));

     $result = curl_exec ($ch);
     $token = json_decode($result, true)['access_token'];
     curl_close($ch);



----------------------------------------------------- Upload File over one drive function -------------------------------

$graph = new Graph();
$graph
->setBaseUrl("https://graph.microsoft.com/")
->setApiVersion("v1.0")
->setAccessToken($token);

$UploadDoc = $graph->createRequest("get", "/me")
->addHeaders(array("Content-Type" => "application/json"))
->setTimeout("1000")
->execute();

$UploadDoc = $graph->createRequest("PUT", "/me/drive/root/children/Screenshot1.png/content")->upload('Screenshot1.png');

     print_r($UploadDoc); die;



Uploading the file api is working correctly while I use the token from graph explorer. ( See screenshot https://prnt.sc/10uyov9).

microsoft-graph-sdk
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

GlenScales-6756 avatar image
0 Votes"
GlenScales-6756 answered testlast-1664 commented

Your using the client_credentials flow but your trying to use the /me endpoint which won't work as there is no workload resources for the associated security principal. Using the /users/{user-id} is the only pattern that will work with client credentials.

· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

![84473-download-1.png][1]

Hello,
After implemented the users/{user-id}, I got new error in below pic.
[1]: /answers/storage/attachments/84473-download-1.png

0 Votes 0 ·
download-1.png (84.9 KiB)