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

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();
            }
        }
    }
}

 

 

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

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值