1
我無法向我們的Dynamics CRM 2016 Web API發出HTTP GET請求以進行概念驗證。動態CRM web api 401獲取Oauth令牌後未經授權
我按照this walk-through創建了一個在Azure Active Directory上設置的多租戶Web應用程序,該應用程序已被授予Dynamics CRM作爲組織用戶的訪問權限。
我使用this example code爲了獲得訪問令牌。這似乎工作,給我看起來像一個有效的令牌。
我使用令牌執行簡單的GET請求,該令牌失敗,出現401 Unauthorized
。代碼:
class Test
{
public async Task RunAsync()
{
var resource = "https://<snip>.crm4.dynamics.com/api/data/v8.1/";
var authParams = AuthenticationParameters.CreateFromResourceUrlAsync(new Uri(resource))
.Result;
var authorityUrl = authParams.Authority;
var resourceUrl = authParams.Resource;
var clientId = "<snip>";
var client_secret = "<snip>";
var clientCredential = new ClientCredential(clientId, client_secret);
var authContext = new AuthenticationContext(authorityUrl, false);
var token = authContext.AcquireToken(resourceUrl, clientCredential);
var response = await CallApiAsync($"{resourceUrl}api/data/v8.1/accounts?$select=name&$top=3", token.AccessToken);
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(response.RequestMessage);
Console.WriteLine(response.Headers);
Console.WriteLine(response.ReasonPhrase);
Console.WriteLine(content);
}
private async Task<HttpResponseMessage> CallApiAsync(string uri, string token)
{
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", token);
httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
return await httpClient.GetAsync(uri);
}
}
}
請求:
Method: GET, RequestUri: 'https://<snip>.crm4.dynamics.com/api/data/v8.1/accounts?$select=name&$top=3', Version: 1.1, Content: <null>, Headers:
{
Authorization: Bearer <snip>
Accept: application/json
OData-MaxVersion: 4.0
OData-Version: 4.0
}
響應:
REQ_ID: <snip>
Strict-Transport-Security: max-age=31536000; includeSubDomains
Date: Tue, 21 Feb 2017 15:08:39 GMT
Set-Cookie: crmf5cookie=<snip>;secure; path=/
Server: Microsoft-IIS/8.5
WWW-Authenticate: Bearer authorization_uri=https://login.windows.net/<snip>/oauth2/authorize,resource_id=https://<snip>.crm4.dynamics.com/
X-Powered-By: ASP.NET
Unauthorized
HTTP Error 401 - Unauthorized: Access is denied
我覺得我失去了一些東西明顯?
感謝這是進步:)使用後一種方法,我現在在'AcquireToken(resourceUrl,clientId,userCredential)'上得到一個異常':'AADSTS70002:請求主體必須包含以下參數:'client_secret或client_assertion'。任何進一步的幫助將不勝感激?似乎沒有接受客戶端憑證和用戶憑證的過載 – ImDarrenG
將身份驗證用作CRM用戶,並將Azure AD中的應用程序設置爲本地而不是Web API,從而使其工作。 – ImDarrenG
請檢查我的答案http://stackoverflow.com/a/43164164/1063168 – PhuocLe