在上篇演示了在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运行代码,身份验证能运行过去并且查询出客户信息。
上述代码有dll依赖,如果是.net core可以使用下述代码
HttpClient _httpClient = new HttpClient();
_httpClient.BaseAddress = new Uri("https://cotoso.crm5.dynamics.com/");
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
_httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
_httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
var content = new FormUrlEncodedContent(new[] {
new KeyValuePair<string,string>("client_id",clientId),
new KeyValuePair<string,string>("username","admin@cotoso.onmicrosoft.com"),
new KeyValuePair<string,string>("password","cotoso"),
new KeyValuePair<string,string>("resource","https://cotoso.crm5.dynamics.com/"),
new KeyValuePair<string,string>("grant_type","password"),
});
var res = _httpClient.PostAsync("https://login.microsoftonline.com/f212d173-9dbb-4612-8467-82f42c776317/oauth2/token", content);
var respo = res.Result.Content.ReadAsStringAsync().Result;
var accesstoken = JObject.Parse(respo).GetValue("access_token").ToString();
本文参考文献:http://www.inogic.com/blog/2016/03/programming-using-webapi-through-c-in-dynamics-crm-2016/