我拥有一个机构电子邮件帐户,我想使用正在编写的PHP Web应用程序访问其内容(并发送电子邮件),并且希望它无需用户登录即可访问该帐户(他们将记录到我的应用程序中,该应用程序将根据用户的操作发送预定义的消息。
我使用此机构帐户凭据在Microsoft Application Registration Portal上注册了该应用程序,并获得了client_id
和client_secret
(密码)。
我正在使用以下代码基于these instructions进行身份验证:
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"
}
}
}
我在这里想念什么或做错什么了?
答案 0 :(得分:1)
您不能将/me
与仅应用验证一起使用,您需要通过其userPrincipalName
-/users/{upn}
来引用用户。毕竟,Graph如何知道您也指的是“我”?