控制台程序(C#)不弹出登录窗口连接到Dynamics CRM Online的Web API
微软动态CRM专家罗勇 ,回复331或者20190505可方便获取本文,同时可以在第一间得到我发布的最新博文信息,follow me!
我之前的文章 控制台程序(C#)不弹出认证窗口连接到Dynamics CRM Online的Web API 发现不好用了,我在stackoverflow上找到了类似的答案,由 IntegerWolf 提供的问题 Using ADAL C# as Confidential User /Daemon Server /Server-to-Server - 401 Unauthorized 的答案。
首先登录 https://portal.azure.com 注册一个app,如下图所示新建:

Name取得有意义即可,Redirect URI得值暂时用不上,然后点击 Register 按钮。

创建成功后将Application (client) ID 和Directory (tenant) ID 复制出来备用。

然后点击左边的 Certificates & secrets ,再点击右边的 New client secret按钮。

直接点击 Add 按钮。

将自动产生的 client secret 复制出来备用。

然后再点击左边的 API permissions ,点击右边的 Add a permission。

将Dynamics CRM Online的如下权限添加上:

再点击下 Grant admin consent for Consoto 按钮,在提示中点击Yes,等待操作完成。

下面就是代码部分了:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Runtime.Serialization.Json;
using System.Threading.Tasks; namespace UsingWebAPI
{
public class AuthenticationResponse
{
public string token_type { get; set; }
public string scope { get; set; }
public int expires_in { get; set; }
public int expires_on { get; set; }
public int not_before { get; set; }
public string resource { get; set; }
public string access_token { get; set; }
public string refresh_token { get; set; }
public string id_token { get; set; }
} public class Account
{
public string name { get; set; } public string telephone1 { get; set; }
}
class Program
{ static string resourceUrl = "https://crm773088.api.crm.dynamics.com/";
static string clientId = "87ca6bd8-3e66-49bd-a756-9c4d86a9ff1a";
static string clientSecret = "iU0@eOCT*Q0r9CGjWdMmJla";
static string tenantId = "79f34dea-50b2-4acf-80e9-700391c4cf83";
static string userName = "admin@CRM773088.onmicrosoft.com";
static string password = "Pas91";
static void Main(string[] args)
{
GetAuthenticationResponse();
Console.ReadKey();
} private static async void GetAuthenticationResponse()
{
List<KeyValuePair<string, string>> vals = new List<KeyValuePair<string, string>>(); vals.Add(new KeyValuePair<string, string>("client_id", clientId));
vals.Add(new KeyValuePair<string, string>("resource", resourceUrl));
vals.Add(new KeyValuePair<string, string>("username", userName));
vals.Add(new KeyValuePair<string, string>("password", password));
vals.Add(new KeyValuePair<string, string>("grant_type", "password"));
vals.Add(new KeyValuePair<string, string>("client_secret", clientSecret));
string url = string.Format("https://login.windows.net/{0}/oauth2/token", tenantId); using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Add("Cache-Control", "no-cache");
HttpContent content = new FormUrlEncodedContent(vals);
HttpResponseMessage hrm = httpClient.PostAsync(url, content).Result; AuthenticationResponse authenticationResponse = null;
if (hrm.IsSuccessStatusCode)
{
Stream data = await hrm.Content.ReadAsStreamAsync();
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(AuthenticationResponse));
authenticationResponse = (AuthenticationResponse)serializer.ReadObject(data);
DataOperations(authenticationResponse);
}
else
{
Console.WriteLine("Error." + hrm.ReasonPhrase);
}
}
} private static async Task DataOperations(AuthenticationResponse authResult)
{
using (HttpClient httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri("https://crm773088.api.crm.dynamics.com/");
httpClient.Timeout = new TimeSpan(, , ); //2 minutes
httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
httpClient.DefaultRequestHeaders.Add("Cache-Control", "no-cache");
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.access_token); Account account = new Account();
account.name = "Test Account";
account.telephone1 = "555-555"; string content = String.Empty;
content = JsonConvert.SerializeObject(account, new JsonSerializerSettings() { DefaultValueHandling = DefaultValueHandling.Ignore });
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "api/data/v9.1/accounts");
request.Content = new StringContent(content);
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
HttpResponseMessage response = await httpClient.SendAsync(request);
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Account '{0}' created.", account.name);
}
else
{
throw new Exception(String.Format("Failed to create account '{0}', reason is '{1}'."
, account.name
, response.ReasonPhrase));
}
}
}
}
}
获取access token的方法用如下的Postman请求模拟也可以获取到。

控制台程序(C#)不弹出登录窗口连接到Dynamics CRM Online的Web API的更多相关文章
- 控制台程序(C#)不弹出认证窗口连接到Dynamics CRM Online的Web API
摘要: 本人微信和易信公众号: 微软动态CRM专家罗勇 ,回复271或者20180602可方便获取本文,同时可以在第一间得到我发布的最新的博文信息,follow me!我的网站是 www.luoyon ...
- QUI操作超时弹出登录窗口登录的处理方式
在使用QUI开发的业务系统中,如果长时间没操作,session过期后,再次操作系统超时会自动跳转到登陆页面,如果当前有一些操作没有保存,需要重新登录后再次填写信息,用户体验很不好! 为了避免超时后页面 ...
- CRM 总是弹出登录窗口
最近测试机总是会出现登录窗口,也能正常进入系统,但是会反复出现. 环境:CRM2016 问题:总是弹出登录窗口 解决方法:
- div弹出登录窗口
<meta charset="utf-8"/> <script type="text/javascript"> //弹出式登录 func ...
- SSO-Javascript模拟IE登录,不让IIS弹出登录窗口
解决方案: 用JS模拟IE用户登录,再跳转到对应的系统. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transiti ...
- 【原创】SSO-Javascript模拟IE登录,不让IIS弹出登录窗口
解决方案: 用JS模拟IE用户登录,再跳转到对应的系统. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN&q ...
- ***小程序wx.getUserInfo不能弹出授权窗口后的解决方案
微信更新api后,wx.getUserInfo在开发和体验版本都不能弹出授权窗口.微信文档说明: 注意:此接口有调整,使用该接口将不再出现授权弹窗,请使用 <button open-type=& ...
- c#自动关闭 MessageBox 弹出的窗口
我们都知道,MessageBox弹出的窗口是模式窗口,模式窗口会自动阻塞父线程的.所以如果有以下代码: MessageBox.Show("内容',"标题"); 则只有关闭 ...
- 第一百三十三节,JavaScript,封装库--弹出登录框
JavaScript,封装库--弹出登录框 封装库,增加了两个方法 yuan_su_ju_zhong()方法,将获取到的区块元素居中到页面,chuang_kou_shi_jian()方法,浏览器窗口事 ...
随机推荐
- ASP.NET Core 2.2 WebApi 系列【七】泛型仓储模式和工作单元
在之前的泛型仓储模式实现中,每个增删改都调用了SaveChanges方法,导致每次更新都提交了事务. 在实际开发过程中,我们经常遇到同时操作多张表数据,那么按照之前的写法,对数据库提交了多次操作,开启 ...
- 原生PHP网页导出和导入excel文件实例
原生PHP实现的网页导出和导入excel文件实例,包括上传也是用的原生.还可在exportExcel方法里设置字体等表格样式. 导出和导入表单代码: <p style="margin: ...
- javaWeb核心技术第四篇之Javascript第二篇事件和正则表达式
- 事件 - 表单提交(掌握) "onsubmit" - 单击事件(掌握) "onclick" - 页面加载成功事件(掌握) "onload" ...
- docker postgres使用
1.拉取镜像文件docker pull postgres 2.容器后台进程运行,向外暴露32769端口 docker run -it --name mypostgres -p 32769:5432 - ...
- 简单sql注入学到的延时盲注新式攻击
0x01 知识点 mysql_pconnect(server,user,pwd,clientflag) mysql_pconnect() 函数打开一个到 MySQL 服务器的持久连接. mysql_p ...
- ABP入门教程8 - 应用层创建应用服务
点这里进入ABP入门教程目录 创建目录 在应用层(即JD.CRS.Application)下创建文件夹Course //用以存放Course相关应用服务 在JD.CRS.Application/Cou ...
- NTP and Chrony在RHEL
在RHEL7上,Chrony已经代替了NTP来做时间同步服务. 1 服务器上操作 yum -y install chrony vim /etc/chrony.conf # Allow NTP clie ...
- Flutter中通过https post Json接收Json
Flutter 已然成为炙手可热前端框架.若问跨平台到底有多香,自然是要多香有多香.今天我就分享这些天研究Flutter http连接和json格式转换的内容,小弟对Flutter也是小白一名,如有错 ...
- liunx用户环境初始化脚本
liunx用户环境初始化脚本 编写生成脚本基本格式,包括作者,联系方式,版本,时间,描述等 [root@magedu ~]# vim .vimrc set ignorecase set c ...
- CK:User mode Bus Error(用户空间操作内核地址导致的异常)
关键词:VEC_ACCESS.coredump.LR.PC等. CK中存在一种VEC_ACCESS异常,可能原因是用户空间访问了内核空间,还有一种是内核访问不存在的总线地址. 下面简单构造VEC_AC ...