簡體   English   中英

如何從Dynamics 365 CRM在線調用第三方REST服務?

[英]How do I call 3rd party REST service from Dynamics 365 CRM online?

我知道這個問題幾乎相同,但是我需要使用訪問令牌來保護呼叫。

因此,當從Dynamics 365 CRM在線調用外部Web api時,我需要設置帶有Bearer令牌的授權請求標頭。

如何獲得隨呼叫發送的訪問令牌?

編輯:我們正在使用Azure廣告在線登錄到Dynamics 365 CRM,這時我們收到保存在cookie中的令牌。

當我們調用外部Web api時,我們希望將該令牌與我們的調用一起作為授權標頭發送。

編輯:

我們嘗試創建一個插件/活動(C#),但是在該上下文中沒有cookie集合(我們可以看到)。 在下面的示例中,我們嘗試使用clientid和clientcredentials,但其中不涉及用戶信息。

using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xrm.Sdk;

namespace MyPlugin
{
    public class TestPlugin : IPlugin
    {
        private const string ClientId = "***";
        private const string ClientSecret = "***";
        private const string AadInstance = "https://login.microsoftonline.com/";
        private const string TenantId = "***";
        private const string PostLogoutRedirectUri = "https://***.crm4.dynamics.com";

        public void Execute(IServiceProvider serviceProvider)
        {
            var tracer = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

            var accessToken = GetTokenWithoutAdal().GetAwaiter().GetResult();
            tracer.Trace(accessToken);

            RetrieveAccounts(accessToken).GetAwaiter().GetResult();
        }

        private static async Task<string> GetTokenWithoutAdal()
        {
            var loginUrl = AadInstance + $"{TenantId}/oauth2/token";

            var client = new HttpClient();
            var postData = $"client_id={ClientId}&client_secret={ClientSecret}&resource={PostLogoutRedirectUri}&grant_type=client_credentials";

            var request = new HttpRequestMessage(HttpMethod.Post, loginUrl) { Content = new StringContent(postData, Encoding.UTF8) };

            request.Content.Headers.Remove("Content-Type");
            request.Content.Headers.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded");
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            var responseMessage = await client.SendAsync(request);

            var jsonResponseString = await responseMessage.Content.ReadAsStringAsync();

            string something = null;
            //Do something

            return something;
        }

        private static async Task<string> RetrieveAccounts(string token)
        {
            var webApiUrl = "https://***.test.com/v1.0";
            var url = $"{webApiUrl}/accounts";

            var client = new HttpClient();
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            var response = await client.GetAsync(url);

            var jsonContent = await response.Content.ReadAsStringAsync();

            return jsonContent;
        }
    }
}

一個同事還嘗試使用Javascript來調用LogicApp,但是沒有發送令牌。

function callLogicApp() {
    fetch('https://dynamicstestapi.azure-api.net/manual/paths/invoke',
            {
                method: 'POST',
                body: JSON.stringify({
                    title: 'foo',
                    body: 'bar',
                    userId: 1
                }),
                credentials: 'include',
                mode: 'cors',
                headers: {
                    'Content-type': 'application/json; charset=UTF-8',
                    'Ocp-Apim-Subscription-Key': 'e1e884bbe9a945a9a4dbcabff49e59d8'
                }
            })
        .then(res => res.json())
        .then(console.log);
}

編輯:

這就是我想要的,用戶訪問令牌(僅來自JWT的有效負載)

{
  "aud": "https://myapi.net",
  "iss": "https://sts.windows.net/******-****-4c1e-b346-2a28ef579dea/",
  "iat": 1567158525,
  "nbf": 1567158525,
  "exp": 1567162425,
  "acr": "1",
  "aio": "ASQA2/8MAAAA1czfs/LOnB0mRwLY****ZF4tHvcoN+oOwpFUE1F6cgU=",
  "amr": [
    "pwd"
  ],
  "appid": "6792c685-bbf7-****-b15f-7b047edd2db6",
  "appidacr": "1",
  "family_name": "Lastname",
  "given_name": "Firstname",
  "ipaddr": "194.114.***.***",
  "name": "Firstname Lastname",
  "oid": "0ba39690-fb32-****-8d6c-3e4826b2f05b",
  "puid": "10030000826E****",
  "scp": "Directory.Read.All User.Read",
  "sub": "3C04Virz0afCxbAfY5****YfNgnC9HR7y3Mqcbgu5wg",
  "tenant_region_scope": "EU",
  "tid": "6f310cfb-5ece-****-b346-2a28ef579dea",
  "unique_name": "fname.lname@domain.com",
  "upn": "fname.lname@domain.com",
  "uti": "U9v1VNGnY0i****-wHlCAA",
  "ver": "1.0"
}

這就是我可以通過clientid和clientsecret獲得的信息(僅來自JWT的有效負載)

{
  "aud": "https://myapi.net",
  "iss": "https://sts.windows.net/******-****-4c1e-b346-2a28ef579dea/",
  "iat": 1567161484,
  "nbf": 1567161484,
  "exp": 1567165384,
  "aio": "42FgYKhpmv0+****3SV/FZvuDbduAA==",
  "appid": "3401bb09-a6f2-****-846a-ef4570b3a8bd",
  "appidacr": "1",
  "idp": "https://sts.windows.net/******-****-4c1e-b346-2a28ef579dea/",
  "oid": "125746e6-4f03-****-8cf9-d568b9fce035",
  "sub": "125746e6-4f03-****-8cf9-d568b9fce035",
  "tid": "6f310cfb-5ece-****-b346-2a28ef579dea",
  "uti": "QiEIwm3560-****ZLz4RAA",
  "ver": "1.0"
}

我已經意識到我的客戶實際上想要身份驗證/授權和跟蹤的結合。

我們還從Microsoft確認,無法在線檢索D365中的用戶訪問令牌並將其與呼叫一起發送給第三方休息服務。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM