IT知识库 购物 网址 游戏 小说 歌词 快照 开发 股票 美女 新闻 笑话 | 汉字 软件 日历 阅读 下载 图书馆 编程 China
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
vbs/VBScript DOS/BAT hta htc python perl 游戏相关 VBA 远程脚本 ColdFusion ruby专题 autoit seraphzone PowerShell linux shell Lua Golang Erlang 其它教程 CSS/HTML/Xhtml html5 CSS XML/XSLT Dreamweaver教程 经验交流 开发者乐园 Android开发资料
站长资讯 .NET新手 ASP.NET C# WinForm Silverlight WCF CLR WPF XNA VisualStudio ASP.NET-MVC .NET控件开发 EntityFramework WinRT-Metro Java C++ PHP Delphi Python Ruby C语言 Erlang Go Swift Scala R语言 Verilog 其它语言 架构设计 面向对象 设计模式 领域驱动 Html-Css JavaScript jQuery HTML5 SharePoint GIS技术 SAP OracleERP DynamicsCRM K2 BPM 信息安全 企业信息 Android开发 iOS开发 WindowsPhone WindowsMobile 其他手机 敏捷开发 项目管理 软件工程 SQLServer Oracle MySQL NoSQL 其它数据库 Windows7 WindowsServer Linux
  IT知识库 -> Dynamics CRM -> crm on premise IFD 部署下提供oauth 2.0 集成自定义应用 -> 正文阅读

[Dynamics CRM]crm on premise IFD 部署下提供oauth 2.0 集成自定义应用

crm on premise IFD 部署下提供oauth 2.0 集成自定义应用 很多情况下我们的CRM系统会和弟三方应用集成,一般情况我们会开发一个中间站点来提供web api 给弟三方应用。
参考:http://alexanderdevelopment.net/post/2015/01/24/authenticating-from-a-node-js-client-to-dynamics-crm-via-ad-fs-and-oauth2/
利用adfs 带的auto2.0可以有一种简单的方式和弟三方应用集成。我们做的只需要类似像和微信、微博、QQ集成弟三登录功能一样实现 ADFS oauth 2.0
弟一步 在ADFS上注册一个client ,生成的 ClientId、RedirectUri (指跳转页面),在ADFS中没有密码这个属性,在请求code的时候 会用这两个属性代替clientid和密码
Add-AdfsClient -ClientId "aa106265-fb3b-49e0-a0e8-6840b3d71ac2" -Name "hongfu dynamics CRM ADFS Client" -RedirectUri "http://localhost:21313/Default.aspx"
弟二步在我们自己的程序中注册登录代码
逻辑比较简单
1 用户进入登录页面

2 用户点击登录,页面会跳转到ADFS的登录页面,注意URL

3 在ADFS实现 登录后,回转到我们之前 定义的RedirectUri,URL中会传一个code参数

4 在登录面的onload 事件中读取出 code,去adfs请求token

 string url = string.Format("{0}adfs/oauth2/token"
            , _adfs);


        string body = string.Format("grant_type=authorization_code&client_id={0}&redirect_uri={1}&code={2}"
            , _clientID, Server.UrlEncode(_returnURL), code);

        var requestJson = JsonConvert.SerializeObject(new
        {
            grant_type = "authorization_code",
            client_id = _clientID,
            redirect_uri = Server.UrlEncode(_returnURL)
        ,
            code = code
        });


        HttpClient client = new HttpClient();
        HttpContent content = new StringContent(body);
        content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
        var tokenstr = client.PostAsync(url, content).Result.Content.ReadAsStringAsync().Result;

5 请求完token后,再使用token调用CRM webapi ,查询出当前用户和客户信息

6 实现 代码如下

using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens;
using System.Linq;
using System.Net;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Net.Http;
using Newtonsoft.Json;
using System.Net.Http.Headers;

public partial class _Default : Page
{


    //

    // Add-AdfsClient -ClientId "aa106265-fb3b-49e0-a0e8-6840b3d71ac2" -Name "hongfu dynamics CRM ADFS Client" -RedirectUri "http://localhost:21313/Default.aspx" 

    private static AuthenticationContext _authenticationContext;

    // TODO Set these string values as approppriate for your app registration and organization.
    // For more information, see the SDK topic "Walkthrough: Register an app with Active Directory".
    private const string _clientID = "aa106265-fb3b-49e0-a0e8-6840b3d71ac2";
    public const string CrmServiceUrl = "https://crm.crmad.com:446/";
    public const string _adfs = "https://adfs.crmad.com/";
    public const string _returnURL = "http://localhost:21313/Default.aspx";

    protected void Page_Load(object sender2, EventArgs e)
    {
        System.Net.ServicePointManager.ServerCertificateValidationCallback =
       ((sender, certificate, chain, sslPolicyErrors) => true);

        if (!string.IsNullOrEmpty(Request["code"]))
        {

            GetToken(Request["code"]);
            //3. Client request access token



        }
    }

    //<snippetModernOdataAppAuthDiscovery>
    /// <summary>
    /// Discover the authentication authority.
    /// </summary>
    /// <param name="serviceUrl">The URL of the organization's SOAP endpoint. </param>
    /// <returns>The authority URL.</returns>
    /// <remarks>The service URL must contain the SdkClient property.</remarks>
    /// <example>https://contoso.crm.dynamics.com/XRMServices/2011/Organization.svc/web?SdkClientVersion=6.1.0.533;</example>
    public static string DiscoveryAuthority(Uri serviceUrl)
    {
        // Use AuthenticationParameters to send a request to the organization's endpoint and
        // receive tenant information in the 401 challenge. 

        HttpWebResponse response = null;
        try
        {
            // Create a web request where the authorization header contains the word "Bearer".
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);

            // The response is to be encoded.
            httpWebRequest.ContentType = "application/x-www-form-urlencoded";
            response = (HttpWebResponse)httpWebRequest.GetResponse();
        }

        catch (WebException ex)
        {
            response = (HttpWebResponse)ex.Response;


        }
        finally
        {
            if (response != null)
                response.Dispose();
        }
        // Return the authority URL.
        return response.ToString();
    }
    //</snippetModernOdataAppAuthDiscovery>



    protected void Button1_Click(object sender, EventArgs e)
    {
        string url = string.Format("{0}adfs/oauth2/authorize?response_type=code&client_id={1}&resource={2}&redirect_uri={3}"
            , _adfs, _clientID, Server.UrlEncode(CrmServiceUrl), Server.UrlEncode(_returnURL));




        Response.Redirect(url);

    }


    public class CRMToken
    {
        public string access_token { get; set; }
        public string token_type { get; set; }

        public string expires_in { get; set; }

        public string refresh_token { get; set; }
    }

    void GetToken(string code)
    {

        string url = string.Format("{0}adfs/oauth2/token"
            , _adfs);


        string body = string.Format("grant_type=authorization_code&client_id={0}&redirect_uri={1}&code={2}"
            , _clientID, Server.UrlEncode(_returnURL), code);

        var requestJson = JsonConvert.SerializeObject(new
        {
            grant_type = "authorization_code",
            client_id = _clientID,
            redirect_uri = Server.UrlEncode(_returnURL)
        ,
            code = code
        });


        HttpClient client = new HttpClient();
        HttpContent content = new StringContent(body);
        content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
        var tokenstr = client.PostAsync(url, content).Result.Content.ReadAsStringAsync().Result;

        var token = JsonConvert.DeserializeObject<CRMToken>(tokenstr);


        using (HttpClient httpClient = new HttpClient())
        {
            httpClient.Timeout = new TimeSpan(0, 2, 0);  // 2 minutes
            httpClient.DefaultRequestHeaders.Authorization =
                new AuthenticationHeaderValue("Bearer", token.access_token);



            //GET [Organization URI]/api/data/v8.1/accounts?$select=name&$top=3 HTTP/1.1
            // Accept: application / json
            //OData - MaxVersion: 4.0
            //OData - Version: 4.0

            var api = string.Format("{0}api/data/v8.1/accounts?$select=name&$top=3", CrmServiceUrl);

            httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
            var str = httpClient.GetStringAsync(api).Result;

            this.TextBox1.Text = str;


        }
        using (HttpClient httpClient = new HttpClient())
        {
            httpClient.Timeout = new TimeSpan(0, 2, 0);  // 2 minutes
            httpClient.DefaultRequestHeaders.Authorization =
                new AuthenticationHeaderValue("Bearer", token.access_token);



            //GET [Organization URI]/api/data/v8.1/accounts?$select=name&$top=3 HTTP/1.1
            // Accept: application / json
            //OData - MaxVersion: 4.0
            //OData - Version: 4.0

            var api = string.Format("{0}api/data/v8.1/WhoAmI()", CrmServiceUrl);

            httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
            var str = httpClient.GetStringAsync(api).Result;

            this.Label1.Text = str;





        }
    }



    protected void Button1_Click1(object sender, EventArgs e)
    {
        string url = string.Format("{0}adfs/oauth2/authorize?response_type=code&client_id={1}&resource={2}&redirect_uri={3}"
            , _adfs, _clientID, Server.UrlEncode(CrmServiceUrl), Server.UrlEncode(_returnURL));




        Response.Redirect(url);
    }
}


<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">

    
    <p>
        <br />
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click1" Text="登录CRM" />
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    </p>
    <p>
        <asp:TextBox ID="TextBox1" runat="server" Height="183px" TextMode="MultiLine" Width="833px"></asp:TextBox>
    </p>

    
</asp:Content>

上一篇文章      下一篇文章      查看所有文章
加:2016-08-22 13:20:30  更:2017-05-16 17:06:35 
 
  Dynamics CRM 最新文章
AX_CreateAndPostPurch
Dynamics CRM用户创建后自动添加到团队报错
AX_Args
[SQL] SQL 基础知识梳理(七)
MSCRM 通过Ajax调用WCF服务
Dynamics CRM 2015
crm on premise IFD 部署下提供oauth 2.0 集
Dynamics CRM用户创建后自动添加到团队报错
Dynamics CRM 之ADFS 使用 WID 的联合服务器
Dynamic CRM 2015学习笔记(2)更改系统显示
技术频道: 站长资讯 .NET新手区 ASP.NET C# WinForm Silverlight WCF CLR WPF XNA Visual Studio ASP.NET MVC .NET控件开发 Entity Framework WinRT/Metro Java C++ PHP Delphi Python Ruby C语言 Erlang Go Swift Scala R语言 Verilog 其它语言 架构设计 面向对象 设计模式 领域驱动设计 Html/Css JavaScript jQuery HTML5 SharePoint GIS技术 SAP Oracle ERP Dynamics CRM K2 BPM 信息安全 企业信息化其他 Android开发 iOS开发 Windows Phone Windows Mobile 其他手机开发 敏捷开发 项目与团队管理 软件工程其他 SQL Server Oracle MySQL NoSQL 其它数据库 Windows 7 Windows Server Linux
脚本语言: vbs/VBScript DOS/BAT hta htc python perl 游戏相关 VBA 远程脚本 ColdFusion ruby专题 autoit seraphzone PowerShell linux shell Lua Golang Erlang 其它教程
网站开发: CSS/HTML/Xhtml html5 CSS XML/XSLT Dreamweaver教程 经验交流 开发者乐园 Android开发资料
360图书馆 软件开发资料 文字转语音 购物精选 软件下载 新闻资讯 小游戏 Chinese Culture 股票 三丰软件 开发 中国文化 网文精选 阅读网 看图 日历 万年历 2018年11日历
2018-11-14 0:47:25
多播视频美女直播
↓电视,电影,美女直播,迅雷资源↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT知识库