[英]Access Microsoft Graph resources with an App access token (no user sign-in)
我擁有一個機構電子郵件帳戶,並且想要使用正在編寫的PHP Web應用程序訪問其內容(並發送電子郵件),並且希望它無需用戶登錄即可訪問該帳戶(它們將被登錄到我的應用程序,它將根據用戶的操作發送預定義的消息)。
我使用此機構帳戶憑據通過Microsoft 應用程序注冊門戶注冊了該應用程序,並獲得了client_id
和client_secret
(密碼)。
我正在使用以下代碼根據這些說明執行身份驗證:
function preformat($string) {
return "<pre>".htmlentities($string)."</pre>";
}
function getGraphAccessToken($domain, $client_id, $password) {
$graph_endpoint="https://graph.microsoft.com/.default";
$token_endpoint = "https://login.microsoftonline.com/".$domain."/oauth2/v2.0/token";
$token_postdata = implode("&",[
"grant_type=client_credentials",
"client_id=".urlencode($client_id),
"client_secret=".urlencode($password),
"scope=".urlencode($graph_endpoint)
]
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_URL, $token_endpoint);
curl_setopt($ch, CURLOPT_POSTFIELDS, $token_postdata);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$token_json = curl_exec($ch);
curl_close($ch);
$token_object = json_decode($token_json);
return "Authorization: ".$token_object->token_type." ".$token_object->access_token;
}
function queryGraph($auth_header, $feed){
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_URL, "https://graph.microsoft.com/v1.0/".$feed);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array($auth_header,"Accept:application/json;odata=minimalmetadata","Content-Type:application/json;odata=minimalmetadata","Prefer:return-content"));
$graph_query = curl_exec($ch);
curl_close($ch);
return $graph_query;
}
$auth_header=getGraphAccessToken($domain,$client_id,$client_secret);
echo preformat($auth_header);
$query_me=queryGraph($auth_header,"me");
echo preformat($query_me);
此代碼成功獲取了訪問令牌,並從https://graph.microsoft.com/v1.0/me/發出了請求,期望收到機構帳戶的信息(作為成功測試)。 但是,我得到以下響應:
{
"error": {
"code": "BadRequest",
"message":
"Current authenticated context is not valid for this request.
This occurs when a request is made to an endpoint that requires user sign-in.
For example, /me requires a signed-in user.
Acquire a token on behalf of a user to make requests to these endpoints.
Use the OAuth 2.0 authorization code flow for mobile and native apps
and the OAuth 2.0 implicit flow for single-page web apps.",
"innerError": {
"request-id": "3073f561-43db-49d3-9851-7f50037abb61",
"date": "2018-12-31T17:28:45"
}
}
}
我在這里想念或做錯了什么?
您不能將/me
與僅用於應用程序的身份驗證一起使用,您需要通過其userPrincipalName
/users/{upn}
來引用該用戶。 畢竟,Graph如何知道您也指的是“我”?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.