2016-08-11 418 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參考的文檔。 –

相關問題