微软动态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的更多相关文章

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

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

  2. QUI操作超时弹出登录窗口登录的处理方式

    在使用QUI开发的业务系统中,如果长时间没操作,session过期后,再次操作系统超时会自动跳转到登陆页面,如果当前有一些操作没有保存,需要重新登录后再次填写信息,用户体验很不好! 为了避免超时后页面 ...

  3. CRM 总是弹出登录窗口

    最近测试机总是会出现登录窗口,也能正常进入系统,但是会反复出现. 环境:CRM2016 问题:总是弹出登录窗口 解决方法:

  4. div弹出登录窗口

    <meta charset="utf-8"/> <script type="text/javascript"> //弹出式登录 func ...

  5. SSO-Javascript模拟IE登录,不让IIS弹出登录窗口

    解决方案:         用JS模拟IE用户登录,再跳转到对应的系统.   <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transiti ...

  6. 【原创】SSO-Javascript模拟IE登录,不让IIS弹出登录窗口

    解决方案: 用JS模拟IE用户登录,再跳转到对应的系统. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN&q ...

  7. ***小程序wx.getUserInfo不能弹出授权窗口后的解决方案

    微信更新api后,wx.getUserInfo在开发和体验版本都不能弹出授权窗口.微信文档说明: 注意:此接口有调整,使用该接口将不再出现授权弹窗,请使用 <button open-type=& ...

  8. c#自动关闭 MessageBox 弹出的窗口

    我们都知道,MessageBox弹出的窗口是模式窗口,模式窗口会自动阻塞父线程的.所以如果有以下代码: MessageBox.Show("内容',"标题"); 则只有关闭 ...

  9. 第一百三十三节,JavaScript,封装库--弹出登录框

    JavaScript,封装库--弹出登录框 封装库,增加了两个方法 yuan_su_ju_zhong()方法,将获取到的区块元素居中到页面,chuang_kou_shi_jian()方法,浏览器窗口事 ...

随机推荐

  1. JAVAEE学期总结

         声明:除第一张思维导图为博主所制作,其他思维导图皆来自网络,若侵权,望告知,必删除.                                                      ...

  2. 通过C#代码调用Dynamics 365 Web API执行批量操作

    我是微软Dynamics 365 & Power Platform方面的工程师罗勇,也是2015年7月到2018年6月连续三年Dynamics CRM/Business Solutions方面 ...

  3. SQLi-LABS Page-3 (order by injections) Less-46-Less-53

    关于order by 注入原理讲解 注入原理 1. 测试 ?sort=1 desc--+?sort=1 asc--+ 显示结果不同,说明可以注入 desc是 descend 降序意思 asc 是 as ...

  4. 2018最新cocoapods详细安装和使用

    1查看当前终端里存在的源 终端输入:$ gem sources -l2移除淘宝镜像 $ gem sources --remove https://rubygems.org/ 3装上目前能用的源 终端输 ...

  5. [20191106]善用column格式化输出.txt

    [20191106]善用column格式化输出.txt # man columnDESCRIPTION     The column utility formats its input into mu ...

  6. python anaconda 常用操作;conda 命令指南

    在使用 python anaconda时,经常会用到很多常用操作,记录下来,方便以后更好地使用: conda: Conda既是一个包管理器又是一个环境管理器.你肯定知道包管理器,它可以帮你发现和查看包 ...

  7. add to explorer context menu需不需要勾选

    添加到鼠标右键菜单,添加以后,可以直接右键文件,直接选择这个软件打开选择的文件,建议勾选

  8. The Preliminary Contest for ICPC Asia Nanjing 2019

    传送门 A. The beautiful values of the palace 题意: 给出一个\(n*n\)的矩阵,并满足\(n\)为奇数,矩阵中的数从右上角开始往下,类似于蛇形填数那样来填充. ...

  9. [C5W2] Sequence Models - Natural Language Processing and Word Embeddings

    第二周 自然语言处理与词嵌入(Natural Language Processing and Word Embeddings) 词汇表征(Word Representation) 上周我们学习了 RN ...

  10. C++ 标准库,可变参数模板。可变参数数量,可变参数类型【转】

    #include <iostream> // 可变模板参数 // 此例:可以构造可变数量,可变类型的函数输入. // 摘自:https://www.cnblogs.com/qicosmos ...