1

我試圖使用PHP和CURL連接到Microsoft Dynamics API,以便我可以從CRM讀取客戶端數據。 API指南可以在這裏找到: https://msdn.microsoft.com/en-gb/library/mt593051.aspx無法使用PHP和Curl連接到Microsoft Dynamics CRM

我已經進入Azure門戶並設置了一個新的應用程序,它給了我使用憑據(客戶端ID,祕密等)和URL結束點。使用這些憑證,我能夠成功連接到CRM並檢索承載訪問令牌,但我無法進一步獲取。

當我嘗試使用令牌返回我收到以下錯誤消息數據:

HTTP錯誤401 - 未經授權:訪問被拒絕

我的假設是,我必須正確傳遞令牌?

我的代碼如下。

<?php 
// Step 1 - Use the credentials supplied by CRM to get an access token (this bit works okay) 
$credentials = array(
    'grant_type'=>'client_credentials', 
    'username'=>'xxxxxxxx', 
    'password'=>'xxxxxxxx', 
    'client_id'=>'xxxxxxxxxxxx', 
    'client_secret'=>'xxxxxxxxxx', 
    ); 
$urlSafeCredentials = http_build_query($credentials); 

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL,'https://login.microsoftonline.com/xxxxxxxxxxxxxx/oauth2/token'); 
curl_setopt($ch, CURLOPT_HEADER, false); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch, CURLOPT_POST, true); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $urlSafeCredentials); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded')); 
$response = curl_exec($ch); 
$result = json_decode($response); 
curl_close($ch); 


// A BEARER access token is successfully returned 
$token = $result->access_token; 


// Step 2 - Use the access token to request data from the CRM (this bit fails with HTTP Error 401 - Unauthorized: Access is denied) 

$ch = curl_init('https://clientspecificurl.crm4.dynamics.com/api/data/v8.1/accounts'); 
curl_setopt($ch, CURLOPT_HEADER, false); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/x-www-form-urlencoded','Authorization: Bearer '.$token)); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
$response = curl_exec($ch); 
curl_close($ch); 
print_r($response); // 401 Unauthorized ?! 
?> 

據我可以告訴有沒有別的在後端配置,任何幫助將不勝感激。

回答

0

基於參數獲取令牌,你是混合客戶端憑證流資源所有者密碼流和缺乏resource參數。

客戶端憑證流需要參數grant_typeclient_idclient_secretresourcegrant_type值爲client_credentials

資源所有者密碼憑據流需要grant_typeclient_idclient_secretusernamepasswordresourcegrant_typepassword

如果您使用的是客戶端憑證流程,則可以參考this blog獲取令牌。如果您使用資源所有者密碼,則可以參考this thread

有關Oauth 2中流量差異的詳細信息,請參閱RFC 6749

0

我寫了一個輕量級的PHP類,用於使用Dynamics 365聯機Web API。你可以找到它here

順便說一句,在你的代碼中,你應該嘗試在grant_type內部而不是「client_credentials」中使用「密碼」

相關問題