摘要: 本人微信和易信公眾號: 微軟動態CRM專家羅勇 ,回復271或者20180602可方便獲取本文,同時可以在第一間得到我發布的最新的博文信息,follow me!我的網站是 www.luoyong.me 。
Dynamics CRM的組織服務(Organization Service) 將會逐漸的退出歷史舞台,取而代之的是Web API.
很多時候會有需求,特別是集成或者開發App,通過代碼連接到Dynamics CRM的Web API,不要彈出窗口要求用戶輸入用戶名和密碼。
如何做,本文介紹,主要內容來自ansrikanth 的 Connect to Dynamics CRM WebApi from Console Application (Without Authentication popup) ,原文是英文的,我這里更新了一些界面,並將主要內容提煉下做成一個比較簡單的介紹。
首先以有權限的賬號(最好是具有Global administrator角色的賬戶)登錄 https://portal.office.com ,點擊左邊的 Admin Centers,選擇Azure AD,就會打開新版的Azure AD管理站點: Azure Active Directory admin Center ,也就是Azure AD管理中心。

在Azure AD管理中心站點中點擊左側的 Azure Active Directory。

然后點擊 應用注冊。

再點擊 新應用注冊。輸入如下所示,名字自己定義,應用程序類型一定要選擇本機 (英文版本的話這里是Native),重定向URI如果沒有特別要求的話設置為 http://localhost/callback 就可以。

創建成功后點擊 【設置】

點擊【所需權限】,再點擊 【添加】

第一步【選擇API】,選擇 【Dynamics CRM Online】,

第二步【選擇權限】,只有 Access Dynamics 365 as organization users 一個可選,選擇它,要求管理員這個選項保持默認為否即可。

完成后的所需權限如下所示:

准備工作做完后,下面我們新建一個控制台應用程序,首先通過NuGet添加對 Microsoft.IdentityModel.Clients.ActiveDirectory 的引用,安裝最新穩定版即可。

下面上代碼,重要的是GetToken 和 GetData 兩個方法。可以看到獲取Token很簡單,因為ADAL已經幫我們封裝好了。大家運行我這個代碼的時候要改動紅色地方為自己的,這里我已經模糊了,你直接運行是跑不起來的。
using Microsoft.IdentityModel.Clients.ActiveDirectory; using System; using System.Net.Http; using System.Net.Http.Headers; using static System.Console; namespace UsingWebAPI { class Program { /// <summary> /// Holds the Authentication context based on the Authentication URL /// </summary> static AuthenticationContext authContext; /// <summary> /// Holds the actual authentication token once after successful authentication /// </summary> static AuthenticationResult authToken; static string apiUrl = "https://luoyongdemo.api.crm5.dynamics.com/api/data"; /// <summary> /// Client ID or Application ID of the App registration in Azure /// </summary> static string clientId = "892F3A98-AA7C-4433-AE88-933A1401320F"; /// <summary> /// The Redirect URL which we defined during the App Registration /// </summary> static string redirectUrl = "http://localhost/callback"; static string userId = "username@sugege.onmicrosoft.com";
static string password = "password";
static void Main(string[] args) { GetToken(); ReadLine(); } internal static async void GetToken() { AuthenticationParameters ap = AuthenticationParameters.CreateFromResourceUrlAsync(new Uri(apiUrl)).Result; string resourceUrl = ap.Resource; string authorityUrl = ap.Authority; authContext = new AuthenticationContext(authorityUrl, false); UserCredential credentials = new UserPasswordCredential(userId, password); //Genertae the AuthToken by using Credentials object. authToken = await authContext.AcquireTokenAsync (resourceUrl, clientId, credentials); WriteLine("Got the authentication token, Getting data from Webapi !!"); GetData(authToken.AccessToken); } internal static async void GetData(string token) { using (HttpClient httpClient = new HttpClient()) { httpClient.Timeout = new TimeSpan(0, 2, 0); // 2 minutes time out period. // Pass the Bearer token as part of request headers. httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); var data = await httpClient.GetAsync("https://luoyongdemo.api.crm5.dynamics.com/api/data/v8.2/accounts?$select=name"); if (data.StatusCode == System.Net.HttpStatusCode.OK) { WriteLine(await data.Content.ReadAsStringAsync()); } else { WriteLine($"Some thing went wrong with the data retrieval. Error code : {data.StatusCode} "); } ReadLine(); } } } }
我展示一個運行成功的例子:

如果是本地部署的做了IFD的Dynamics 365,請參考這篇文章: https://www.cnblogs.com/WJvsToo/p/Dynamics365-WebAPI-ADFS-token.html
