控制台程序(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,不要弹出窗口要求用户输入用户名和密码。
如何做,本文介绍,主要内容来自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(, , ); // 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
控制台程序(C#)不弹出认证窗口连接到Dynamics CRM Online的Web API的更多相关文章
- 控制台程序(C#)不弹出登录窗口连接到Dynamics CRM Online的Web API
微软动态CRM专家罗勇 ,回复331或者20190505可方便获取本文,同时可以在第一间得到我发布的最新博文信息,follow me! 我之前的文章 控制台程序(C#)不弹出认证窗口连接到Dynami ...
- ***小程序wx.getUserInfo不能弹出授权窗口后的解决方案
微信更新api后,wx.getUserInfo在开发和体验版本都不能弹出授权窗口.微信文档说明: 注意:此接口有调整,使用该接口将不再出现授权弹窗,请使用 <button open-type=& ...
- c#自动关闭 MessageBox 弹出的窗口
我们都知道,MessageBox弹出的窗口是模式窗口,模式窗口会自动阻塞父线程的.所以如果有以下代码: MessageBox.Show("内容',"标题"); 则只有关闭 ...
- QUI操作超时弹出登录窗口登录的处理方式
在使用QUI开发的业务系统中,如果长时间没操作,session过期后,再次操作系统超时会自动跳转到登陆页面,如果当前有一些操作没有保存,需要重新登录后再次填写信息,用户体验很不好! 为了避免超时后页面 ...
- pyqt5对用qt designer设计的窗体实现弹出子窗口的示例
pyqt5对用qt designer设计的窗体实现弹出子窗口的示例 脚本专栏 python 1. 用qt designer编写主窗体,窗体类型是MainWindow,空白窗口上一个按钮.并转换成mai ...
- SpringBooot- 访问时,默认有弹出认证
SpringBooot- 访问时,默认有弹出认证 springboot启动成功后,访问请求时,默认弹出窗口,需登录认证. 原因: 是由于使用了springsecurity的默认安全策略,解决方案:启动 ...
- JS弹出模态窗口下拉列表特效
效果体验:http://hovertree.com/texiao/js/20/ 或者扫描二维码在手机体验: 点击选择城市后,在弹出的层中的输入框,输入英文字母 h,会有HoverTree和Hewenq ...
- JS设置弹出小窗口。
经常上网的朋友可能会到过这样一些网站,一进入首页立刻会弹出一个窗口,或者按一个连接或按钮弹出,通常在这个窗口里会显示一些注意事项.版权信息.警告.欢迎光顾之类的话或者作者想要特别提示的信息.其实制作这 ...
- JS 弹出模态窗口解决方案
最近在项目中使用弹出模态窗口,功能要求: (1)模态窗口选择项目 (2)支持选择返回事件处理 在IE中有showModalDialog 方法,可以很好的解决该问题,但是在Chrome中和FF中就有问题 ...
随机推荐
- ML-Framework:ML.NET 0.3 带来新组件
ML.NET在今年微软在Build 2018 会议上宣布的机器学习框架现已正式推出0.3版本 https://github.com/dotnet/machinelearning/releases/ta ...
- 1.5 A better alternative thing: React Native
In 2015, React Native (RN) was born. At that time, few people paid attention to it because it was st ...
- Echarts 几个常用图
最近公司业务上的 需求,要求做一些图表,我们技术框架上选择方便使用的Echarts. 下面是效果图: 下面是具体代码: <!DOCTYPE html> <html> <h ...
- HTML5 history.pushState()和history.replaceState()新增、修改历史记录用法介绍
抽空研究了下这两个新方法,确实可以解决很多问题 1.使用pushState()方法 可以控制浏览器自带的返回按钮: 有时候我们想让用户点击浏览器返回按钮时,不返回,或执行其他操作,这时,就用到hist ...
- OSGi类加载流程
思路 OSGi每个模块都有自己独立的classpath.如何实现这一点呢?是因为OSGi采取了不同的类加载机制: OSGi为每个bundle提供一个类加载器,该加载器能够看到bundle Jar文件内 ...
- [Swift]LeetCode283. 移动零 | Move Zeroes
Given an array nums, write a function to move all 0's to the end of it while maintaining the relativ ...
- [Swift]LeetCode481. 神奇字符串 | Magical String
A magical string S consists of only '1' and '2' and obeys the following rules: The string S is magic ...
- Redis 设计与实现 (二)--数据库
typedef struct redisDb { dict *dict; /* The keyspace for this DB */ dict *expires; /* Timeout of key ...
- 微信小程序请求API接口PHPSESSID变化的解决方式
微信小程序开发,请求服务器API的方法使用的是微信官方提供的wx.request()方法.在开发中发现,每一个请求都会生成一个独立的PHPSESSID,如下图示: 搜索后得知,这是由于wx.reque ...
- CoCos2dx开发:tile地图绘制和Tiled工具的基本使用
1.新建地图: 在Tiled工具里新建文件: 设置地图的地图大小和地图块大小: 新建好的空文件如下: 2.绘制图块: 在Aseprite中建立相应大小(注意:划分的图块为32*32,因此图片大小最好与 ...