控制台程序(C#)不弹出认证窗口连接到Dynamics CRM Online的Web API

摘要: 本人微信和易信公众号: 微软动态CRM专家罗勇 ,回复271或者20180602可方便获取本文,同时可以在第一间得到我发布的最新的博文信息,follow me!我的网站是 www.luoyong.me 。

Dynamics CRM的组织服务(Organization Service) 将会逐渐的退出历史舞台,取而代之的是Web API.

很多时候会有需求,特别是集成或者开发App,通过代码连接到Dynamics CRM的Web API,不要弹出窗口要求用户输入用户名和密码。

如何做,本文介绍,主要内容来自 的 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(); } } } }

我展示一个运行成功的例子:

猜你喜欢

转载自www.cnblogs.com/luoyong0201/p/Connect_To_Dynamics_365_Online_Using_ADAL_Without_Authentication_Popup.html