Dynamics 365Online Server-Side OAuth身份认证
在上篇演示了在html页面中通过调用online的OAuth身份验证后再通过web api取10条客户数据并展示,本篇继续讲述如何在server-side程序中调用online的OAuth认证再通过web api取客户数据。azure的应用程序设置本篇就不做过多说明,可参照上篇,在设置应用程序的类型时有些区别,这里选择的是本机客户端应用程序。
贴上源代码
string resource = "https://skysoft002.crm5.dynamics.com";
string clientId = "1e076b65-327d-4244-b9c6-1e0d120eb667";
AuthenticationContext authContext =
new AuthenticationContext("https://login.windows.net/common", false);
AuthenticationResult result = authContext.AcquireToken(resource, clientId,
new UserCredential(username, pwd)); ;
using (HttpClient httpClient = new HttpClient())
{
httpClient.Timeout = new TimeSpan(0, 2, 0);// 2 minutes
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", result.AccessToken);
httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
HttpResponseMessage response = httpClient.GetAsync(
"https://skysoft002.crm5.dynamics.com/api/data/v8.2/accounts?$top=1").Result;
String returnvalue = response.Content.ReadAsStringAsync().Result;
} 这里需要引用命名空间Microsoft.IdentityModel.Clients.ActiveDirectory,直接在nuget中下载即可,但要注意的是3.0版本以后AuthenticationContext已经没有AcquireToken这个方法了,所以如果你直接下载的最新版再引用SDK中的代码时会报错,你下载3.0以下版本就可以了。
最后F5运行代码,身份验证能运行过去并且查询出客户信息。
本文参考文献:http://www.inogic.com/blog/2016/03/programming-using-webapi-through-c-in-dynamics-crm-2016/
页:
[1]