访问Calendar API返回401 Unauthorized

时间:2016-05-10 11:01:16

标签: authorization office365api office365-restapi

我是Office 365的新手,并且在访问rest api时遇到问题。 我正在尝试测试日历和邮件API 的其余API,所以我决定使用Postman。但是,要测试这些API,我需要在Authorization标头中使用访问令牌。为了弄清楚如何获取令牌,我决定获取示例项目here,配置,运行并登录此本地站点以获取缓存在本地存储中的令牌,并使用该令牌在Postman中进一步请求。但是,我测试的所有请求都返回了“401未经授权的请求”。

我做了什么:

  • 在与O365帐户关联的Azure ADD上注册新应用
  • 添加完整的应用权限和委派的权限。
  • 在清单文件中将'oauth2AllowImplicitFlow'更新为true。
  • 克隆示例项目
  • 在app.js中,我将配置功能的内容更改为以下

    function config($routeProvider, $httpProvider, adalAuthenticationServiceProvider) {
        $routeProvider
        .when('/', {
            templateUrl: 'views/home.html',
            controller: 'HomeController',
            controllerAs: 'home',
            requireADLogin: true
        })
    
        .otherwise({
            redirectTo: '/'
        });
    
    // The endpoints here are resources for ADAL to get tokens for.
    var endpoints = {
        'https://outlook.office365.com': 'https://outlook.office365.com'
    };
    
    // Initialize the ADAL provider with your tenant name and clientID (found in the Azure Management Portal).
    adalAuthenticationServiceProvider.init(
        {
            tenant: 'mytenantname.onmicrosoft.com',
            clientId: '<my cliend Id>',
            endpoints: endpoints,
            cacheLocation: 'localStorage'
        },
        $httpProvider
        );
    };
    

然后我运行了应用程序,它签好了,我也可以获得令牌,但该令牌也未经授权请求。 我解码了令牌并看到了'aud'的值,它没有返回“https://outlook.office365.com/”。在this url中,作者说“这应该是”https://outlook.office365.com/“用于邮件,日历或通讯录API”

那我错过了什么?

1 个答案:

答案 0 :(得分:1)

如何在AngularJS中调用Office 365 API?

在对用户进行签名时,您只会获得id_token以对用户进行身份验证。

id_token的aud是租户ID(GUID)。

要调用Office 365 API,您需要使用AugularJS http请求。

以下是使用AngularJS中的Microsoft Graph API发送电子邮件的示例:

  // Build the HTTP request to send an email.
  var request = {
    method: 'POST',
    url: 'https://graph.microsoft.com/v1.0/me/microsoft.graph.sendmail',
    data: email
  };

  // Execute the HTTP request. 
  $http(request)
    .then(function (response) {
      $log.debug('HTTP request to Microsoft Graph API returned successfully.', response);     
      response.status === 202 ? vm.requestSuccess = true : vm.requestSuccess = false; 
      vm.requestFinished = true;
    }, function (error) {
      $log.error('HTTP request to Microsoft Graph API failed.');
      vm.requestSuccess= false;
      vm.requestFinished = true;
    });

在调用API之前,ADAL.js将获取另一个令牌 - 您可以用来发送电子邮件的访问令牌。

enter image description here

<强>更新#1

我还下载了你提到的样本。要运行此示例,请确保您拥有 Exchange Online&gt;读取和写入用户邮件在您的应用程序中分配的权限。

enter image description here

相关问题