我正在使用adal.js通过Microsoft OAuth生成访问令牌,但每当我尝试使用访问令牌调用https://graph.microsoft.com/v1.0/me
端点(或graph.windows.net)时,我都会收到以下错误: Authentication_MissingOrMalformed:访问令牌丢失或格式错误。
关于如何解决这个问题的任何想法?这是我在JS中的配置:
<script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.12/js/adal.min.js"></script>
<script>
var authContext = new AuthenticationContext({
instance: 'https://login.microsoft.com/',
tenant: 'xxxxxx-xxxxxxx-xxxxxx-xxxxxx', //COMMON OR YOUR TENANT ID
clientId: 'xxxxxx-xxxxxxx-xxxxxx-xxxxxx', //REPLACE WITH YOUR CLIENT ID
redirectUri: '/login.php', //REPLACE WITH YOUR REDIRECT URL
callback: getUser,
popUp: true,
cacheLocation: 'localStorage'
});
...
authContext.login();
// SET COOKIE
var newToken = authContext.getCachedToken('tenantid-xxxxxxx-xxxxxx-xxxxxx');
var now = new Date();
now.setTime(now.getTime() + 1 * 3600 * 1000);
document.cookie = "token="+newToken+"; expires=" + now.toUTCString() + "; path=/";
</script>
以下是我在PHP脚本中尝试提取/使用令牌的方法:
<?php
// Get the token
$token = $_COOKIE['token'];
// Set headers
$headers = array(
"Authorization: Bearer " . $token,
'Content-Type: application/json'
);
// Make request to Graph API
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://graph.windows.net/mywebsite.org/me?api-version=1.6");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$response = json_decode($response);
curl_close($ch);
echo "<pre>";
var_dump($response);
echo "</pre>";
?>
它只是返回此错误: Authentication_MissingOrMalformed:访问令牌丢失或格式错误。
我该如何解决这个问题?没有指定正确的资源是一个问题吗?
答案 0 :(得分:0)
要成功调用Azure AD Graph REST,我们需要获取Azure AD Graph的令牌。
要检查令牌是否适用于Azure AD Graph,您可以打印令牌并从here解析它。
令牌中的aud
声明应为https://graph.windows.net
。如果它不匹配,则需要使用acquireToken
获取令牌,而不是从缓存中获取令牌。 resource
参数应为https://graph.windows.net
。