首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ADAL.js -获取图API资源的令牌

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

Stack Overflow用户
提问于 2017-07-11 21:43:35
回答 1查看 8.3K关注 0票数 3

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

我的问题非常类似于:令牌 .但答案并没有告诉我足够的代码让我上路。

到目前为止,仅使用adal.js (v1.0.14),我就可以登录&获得一个id_token,但我不知道如何使用它来访问图形API调用。

更新:我知道我正确地注册到Azure门户,因为我能够登录并获得没有adal.js或任何库的最近的文档.只是使用自制的ajax呼叫。

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

代码语言:javascript
复制
// 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:我更改了每个acquireToken的答案,但是现在当adal为我的资源默默地获得一个访问令牌时,它无法将它传递给我的API调用。

更新代码:

代码语言:javascript
复制
    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_token。但是,acquireToken将一个null令牌传递给图形API调用。

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

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-07-12 06:29:48

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

如果您在Azure门户上注册应用程序,要获得MicrosoftGraph的访问令牌,您需要用authContext.config.clientId替换https://graph.microsoft.com

要想让其他人成功,我们需要确保得到足够的许可。例如,要列出最近的文件,需要下列范围之一:Files.ReadFiles.ReadWriteFiles.Read.AllFiles.ReadWrite.AllSites.Read.AllSites.ReadWrite.All(参考这里)。

更新

代码语言:javascript
复制
<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>
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45044964

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档