Javascript ADAL.js-获取图形API资源的令牌

Javascript ADAL.js-获取图形API资源的令牌,javascript,microsoft-graph-api,adal.js,Javascript,Microsoft Graph Api,Adal.js,我正在React中开发一个SPA应用程序,需要与AzureAD和GraphAPI(隐式流)集成 我的问题非常类似于:。。。但是答案没有给我足够的代码让我上路 到目前为止,仅使用adal.js(v1.0.14),我就可以登录并获取id_令牌,但我不知道如何使用它来访问Graph API调用 更新:我知道我已经正确注册了Azure门户,因为我能够在没有adal.js或任何lib的情况下登录并获取最新文档。。。只是使用自制的ajax调用 这是我的代码,它执行登录/重定向,然后尝试获取我最近的文档: /

我正在React中开发一个SPA应用程序,需要与AzureAD和GraphAPI(隐式流)集成

我的问题非常类似于:。。。但是答案没有给我足够的代码让我上路

到目前为止,仅使用adal.js(v1.0.14),我就可以登录并获取id_令牌,但我不知道如何使用它来访问Graph API调用

更新:我知道我已经正确注册了Azure门户,因为我能够在没有adal.js或任何lib的情况下登录并获取最新文档。。。只是使用自制的ajax调用

这是我的代码,它执行登录/重定向,然后尝试获取我最近的文档:

// Initial setup      
var adalCfg = {
  instance              : 'https://login.microsoftonline.com/',
  tenant                : 'common',
  clientId              : 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
  postLogoutRedirectUri : window.location.origin,
  extraQueryParameter   : 'scope=Mail.ReadWrite+Files.Read+Files.ReadWrite+User.ReadBasic.All' // Is this the proper way to specify what resources I need access to?
};

var authContext = new Adal(adalCfg);

if(!authContext.getCachedUser()) {
  authContext.login();  // redirects MS login page successfully
}

// Check For & Handle Redirect From AAD After Login
var isCallback = authContext.isCallback(window.location.hash); // Checks if the URL fragment contains access token, id token or error_description.
if(isCallback) {
  authContext.handleWindowCallback(); // extracts the hash, processes the token or error, saves it in the cache and calls the registered callbacks with the result.
}

if (isCallback && !authContext.getLoginError()) {
  window.location = authContext._getItem(authContext.CONSTANTS.STORAGE.LOGIN_REQUEST); // redirects back to /
}

// Try to get my recent docs - FAILS with InvalidAuthenticationToken error
// UDPATED authContext.acquireToken(authContext.config.clientId, function (error, token) {
authContext.acquireToken('https://graph.microsoft.com', function (error, token) {

  $.ajax({
    url: 'https://graph.microsoft.com/v1.0/me/drive/recent',
    headers:{'authorization':'Bearer '+ token},
    type:'GET',
    dataType:'json'
  }).done(function(res) {
    console.log(res['value']);
  });

});
我做错了什么


更新2:我根据Fei的回答更改了
acquireToken
,但现在当adal静默地获取我的资源的访问令牌时,它无法将其传递给我的API调用

更新代码:

    adalCfg.endpoints.graphApiUri = "https://graph.microsoft.com";

    authContext.acquireToken(adalCfg.endpoints.graphApiUri, function (errorDesc, token, error) {
      console.log('errorDesc = ' + errorDesc)
      console.log('token = ' + token)      
      console.log('error = ' + error)

      $.ajax({
        url: adalCfg.endpoints.graphApiUri + '/v1.0/me/drive/recent',
        headers:{'authorization':'Bearer '+ token},
        type:'GET',
        dataType:'json'
      }).done(function(res) {
        console.log(res['value']);
      });

    });
和控制台输出:

该图显示了令牌的req,它似乎成功了,因为下一个GET在散列中包含
access\u令牌
。但是,
acquireToken
null
标记传递给我的图形API调用

但是,如果我手动从哈希中获取访问令牌,我可以成功地进行Graph API调用


为什么adal不将访问令牌传递给我的API调用?它回来了,并且是有效的

要调用Microsoft Graph,我们需要获取此资源的特定令牌。根据您使用
authContext.config.clientId
获取令牌的代码

如果您在Azure portal上注册应用程序,要获取Microsoft Graph的访问令牌,您需要将
authContext.config.clientId
替换为
https://graph.microsoft.com

要成功地呼叫其他人,我们需要确保有足够的权限。例如,要列出最近的文件,需要下列作用域之一:
文件.Read
文件.ReadWrite
文件.Read.All
文件.ReadWrite.All
站点.Read.All
站点.ReadWrite.All
(请参阅)

更新

登录
点击我
$(函数(){
变量端点={
"https://graph.microsoft.com": "https://graph.microsoft.com"
};
window.config={
租户:“xxxx.onmicrosoft.com”,
客户ID:'XXXXXXXXXXXXXX',
端点:端点
};
window.authContext=新的AuthenticationContext(配置);
$(“#登录”)。单击(函数(){
window.authContext.login();
});
$(“#单击我”)。单击(函数(){
var user=window.authContext.getCachedUser();
console.log(用户);
window.authContext.acquireToken('https://graph.microsoft.com,函数(错误,标记){
console.log(错误);
console.log(令牌);
$.ajax({
网址:'https://graph.microsoft.com/v1.0/me/',
标头:{'authorization':'Bearer'+令牌},
类型:'GET',
数据类型:'json'
}).完成(功能(res){
log(res['userPrincipalName']);
});
});
}
);
函数init(){
if(window.location.hash!=“”)
window.authContext.handleWindowCallback(window.location.hash);
}
init();
});

https://graph.windows.net
。我还更新了帖子,添加了一个调用MicrosoftGraph的代码示例。如果您仍然存在此问题,您可以共享一个可运行的代码示例来帮助复制此问题。此问题是否已修复?如果没有,请检查我更新的代码示例,看看它是否有用。如果你仍然有问题,你可以分享一个可运行的代码示例来帮助我们重现这个问题。回到这个-@FeiXue MSFT,是的,你的代码示例对我有用。我接受了你的回答。我从哪里得到客户ID?我们在Azure AD中注册了一个具有Graph API权限的应用程序。我想在Azure之外的web服务器上托管此代码(与已注册的应用程序无关),但不想注册它。此外,我如何使用或应该使用已注册应用程序的应用程序机密和回复URL?您好,有时间吗?我面临着类似的问题,我可以使用adal登录,但当我在标题中传递令牌时,就像上面提到的一样,它返回以下响应{“error”:{“code”:“InvalidAuthenticationToken”,“message”:“访问令牌验证失败”。,“innerError”:{“请求id”:“2600e8e9-27ea-488a-a5ab-cae0d4200e7c”,“日期”:“2018-06-29T11:30:00”}}}}}我在项目中使用adal.js,当我调用graph api时,当我通过“”而不是客户端id时,我会注销
<html>
<head>
<script src="\node_modules\jquery\dist\jquery.js"></script>
<script src="node_modules\adal-angular\lib\adal.js"></script>
</head>
<body>

<button id="login"> login</button>
<button id="clickMe">click me</button>
<script>


$(function () {
    var endpoints = {
          "https://graph.microsoft.com": "https://graph.microsoft.com"
    };
    window.config = {
        tenant: 'xxxx.onmicrosoft.com',
        clientId: 'xxxxxxxxxxxxxxxxx',
        endpoints: endpoints
    };
    window.authContext = new AuthenticationContext(config);


    $("#login").click(function () {
        window.authContext.login();
    });

    $("#clickMe").click(function () {
        var user = window.authContext.getCachedUser();
        console.log(user);

        window.authContext.acquireToken('https://graph.microsoft.com', function (error, token) {
            console.log(error);
            console.log(token);

             $.ajax({
        url: 'https://graph.microsoft.com/v1.0/me/',
        headers:{'authorization':'Bearer '+ token},
        type:'GET',
        dataType:'json'
      }).done(function(res) {
        console.log(res['userPrincipalName']);
      });

    });
        }
            );

    function init(){
        if(window.location.hash!="")
            window.authContext.handleWindowCallback(window.location.hash);
    }

    init();
});
</script>


</body>
</html>