2016-08-11 586 views
0

我正在尝试进行身份验证并签入OneDrive for business以获取访问令牌。使用OneDrive API获取访问令牌

我已经在Azure Active Directory中注册了我的应用程序,并获得了我的client_Id和我的Client_Secret。基于OneDrive API Documentation,下一步是登录以获取将用于获取访问令牌的授权码。我能够顺利拿到代码,但下一步是具有以下参数的POST:

POST https://login.microsoftonline.com/common/oauth2/token

内容类型:应用程序/ x-WWW窗体-urlencoded

参数:

client_id: 
redirect_uri: 
client_secret: 
code: 
resource: The resource you want to access. ???? 

至此我怎么知道要访问的资源,目前还不清楚为这个参数发送什么值。

我离开它空的,我收到了“访问控制允许来源”错误:

的XMLHttpRequest无法加载https://login.microsoftonline.com/common/oauth2/token。请求的资源上没有“Access-Control-Allow-Origin”标题。因此'Origin'http://localhost:23320'不允许访问。响应有HTTP状态代码400

这是我的代码:

var bodyInfo = { 
     client_id: {client_id}, 
     redirect_uri: {redirect_uri}, 
     client_secret: {client_secret}, 
     code: {code}, 
     grant_type: 'authorization_code', 
     resource:????? 

    }; 

    $.ajax({ 
     url: "https://login.microsoftonline.com/common/oauth2/token", 
     type: "POST", 
     data: bodyInfo, 
     success: function (data, textStatus, jqXHR) { 
      window.alert("Saved successfully!"); 
     }, 
     error: function (jqXHR, textStatus, errorThrown) { 

     } 
    }); 

我真的很感激任何帮助。

回答

1

要知道你需要,你应该冷杉使用Office的资源发现API(和第一身份验证吧):

In most cases, the OneDrive for Business API endpoint URL will not be known. To discovery the endpoint URL, you need to make a call to the Office 365 Discovery API. To authenticate with the discovery API, you need to request an access token for resource https://api.office.com/discovery/ . Make sure to include the trailing/character, otherwise your app will be denied access to the discovery API.

然后,你需要获得服务数据(步骤3)

GET https://api.office.com/discovery/v2.0/me/services 
Authorization: Bearer {access_token} 

访问令牌应该在步骤2的响应上。

响应应该是这样的:

{ 
    "@odata.context": "https:\/\/api.office.com\/discovery\/v1.0\/me\/$metadata#allServices", 
    "value": [ 
    { 
     "@odata.type": "#Microsoft.DiscoveryServices.ServiceInfo", 
     "capability": "MyFiles", 
     "serviceApiVersion": "v2.0", 
     "serviceEndpointUri": "https:\/\/contoso-my.sharepoint.com\/_api\/v2.0", 
     "serviceResourceId": "https:\/\/contoso-my.sharepoint.com\/" 
    } 
    ] 
} 

然后你应该找到serviceResourceId(在数组数组中的json对象内),并用它来获得一个驱动器的正确标记(步骤4)。

+0

任何想法如何使用办公室的发现API?我找不到一个明确的例子。 –

+0

[这里](https://msdn.microsoft.com/en-us/office/office365/api/discovery-service-rest-operations)是发现服务REST API参考的文档。 –