簡體   English   中英

如何將服務器服務連接到Dynamics Online

[英]How do I connect a server service to Dynamics Online

我正在修改內部管理應用程序以連接到我們的在線托管Dynamics 2016實例。

在一些在線教程之后,我一直在使用SDK中的Microsoft.Xrm.Sdk.ClientOrganizationServiceProxy

這似乎需要一個用戶名和密碼來連接,這很好,但我想以某種方式連接,不需要特定用戶的帳戶詳細信息。 我不認為我見過的OAuth示例是合適的,因為沒有用戶界面,也沒有真人來顯示OAuth請求。

public class DynamicsHelper
{
    private OrganizationServiceProxy service;

    public void Connect(string serviceUri, string username, string password)
    {
            var credentials = new ClientCredentials();
            credentials.UserName.UserName = username;
            credentials.UserName.Password = password;

            var organizationUri = new Uri(serviceUri);
            this.service = new OrganizationServiceProxy(organizationUri, null, credentials, null);
    }
}

有沒有辦法連接應用程序令牌或API密鑰?

使用Microsoft Dynamics CRM Online或面向Internet的部署使用Web Online for CRM Online或本地面向Internet的部署(IFD)時, 必須使用OAuth ,如使用OAuth連接到Microsoft Dynamics CRM Web服務中所述。

在使用OAuth身份驗證連接CRM Web服務之前, 必須首先在 Microsoft Azure Active Directory中注冊您的應用程序 Azure Active Directory用於驗證是否允許您的應用程序訪問存儲在CRM租戶中的業務數據。

 // TODO Substitute your correct CRM root service address, 
 string resource = "https://mydomain.crm.dynamics.com";

// TODO Substitute your app registration values that can be obtained after you
// register the app in Active Directory on the Microsoft Azure portal.
string clientId = "e5cf0024-a66a-4f16-85ce-99ba97a24bb2";
string redirectUrl = "http://localhost/SdkSample";


// Authenticate the registered application with Azure Active Directory.
AuthenticationContext authContext = 
    new AuthenticationContext("https://login.windows.net/common", false);
AuthenticationResult result = 
    authContext.AcquireToken(resource, clientId, new Uri(redirectUrl));

PS:關於您的方法,最佳做法是將密碼存儲為明文,加密或加密配置部分以獲得最大安全性。

請看這里的walkhrough

希望這可以幫助 :)

如果我正確理解您的問題,您希望通過帶有ClientId和Secret的注冊Azure應用程序而不是用戶名和密碼連接到Dynamics 2016(Dynamics 365)。 如果這是正確的,那么可以使用OrganizationWebProxyClient 您甚至可以使用強類型程序集。

var organizationWebProxyClient = new OrganizationWebProxyClient(GetServiceUrl(), true);
organizationWebProxyClient.HeaderToken = authToken.AccessToken;

OrganizationRequest request = new OrganizationRequest()
{
    RequestName = "WhoAmI"
};

WhoAmIResponse response = organizationWebProxyClient.Execute(new WhoAmIRequest()) as WhoAmIResponse;
Console.WriteLine(response.UserId);

Contact contact = new Contact();
contact.EMailAddress1 = "jennie.whiten@mycompany.com";
contact.FirstName = "Jennie";
contact.LastName = "White";
contact.Id = Guid.NewGuid();

organizationWebProxyClient.Create(contact);

要獲取AccessToken,請參閱以下文章從控制台應用程序連接到Dynamics CRM WebApi

替換第66行(完整源代碼)

authToken = await authContext.AcquireTokenAsync(resourceUrl, clientId, new Uri(redirectUrl), new PlatformParameters(PromptBehavior.Never));

authToken = await authContext.AcquireTokenAsync( resourceUrl, new ClientCredential(clientId, secret));

您還可以檢查以下鏈接驗證Azure功能應用程序以連接到在線Dynamics 365 CRM ,其中介紹了如何使用Azure Key Vault保護憑據。

我發現要成功完成此操作,您需要設置以下所有內容:

  1. 在Azure AD中創建應用程序注冊:
    • 授予它對Dynamics的API權限,特別是“Access Dynamics 365 as organization users”
    • 給它一個虛擬的web重定向URI,例如http://localhost/auth
    • 生成客戶端密鑰並保存以供日后使用
  2. 在Azure AD中創建用戶帳戶並為其授予Dynamics權限。
  3. 使用與上述非交互式用戶帳戶相同的電子郵件在Dynamics中創建應用程序用戶記錄。
  4. 使用您創建的用戶帳戶驗證您的應用程序。

對於第4步,您需要打開一個新的隱身窗口,使用以下模式構建網址並使用您在步驟2中的用戶帳戶憑據登錄:

https://login.microsoftonline.com/<your aad tenant id>/oauth2/authorize?client_id=<client id>&response_type=code&redirect_uri=<redirect uri from step 1>&response_mode=query&resource=https://<organization name>.<region>.dynamics.com&state=<random value>

完成此操作后,您應該看到您的Dynamics應用程序用戶具有應用程序ID和應用程序ID URI。

現在使用ClientId和ClientSecret以及一些其他組織特定變量,您可以使用Azure Active Directory(AAD)進行身份驗證以獲取oauth令牌並構建OrganizationWebProxyClient 我從來沒有找到完成此代碼的完整代碼示例,但我已經為自己的目的開發了以下內容。 請注意,您獲得的令牌的有效期為1小時。

internal class ExampleClientProvider
{
    // Relevant nuget packages:
    // <package id="Microsoft.CrmSdk.CoreAssemblies" version="9.0.2.9" targetFramework="net472" />
    // <package id="Microsoft.IdentityModel.Clients.ActiveDirectory" version="4.5.1" targetFramework="net461" />

    // Relevant imports:
    // using Microsoft.IdentityModel.Clients.ActiveDirectory;
    // using Microsoft.Crm.Sdk.Messages;
    // using Microsoft.Xrm.Sdk;
    // using Microsoft.Xrm.Sdk.Client;
    // using Microsoft.Xrm.Sdk.WebServiceClient;

    private const string TenantId = "<your aad tenant id>";                 // from your app registration overview "Directory (tenant) ID"
    private const string ClientId = "<your client id>";                     // from your app registration overview "Application (client) ID"
    private const string ClientSecret = "<your client secret>";             // secret generated in step 1
    private const string LoginUrl = "https://login.microsoftonline.com";    // aad login url
    private const string OrganizationName = "<your organization name>";     // check your dynamics login url, e.g. https://<organization>.<region>.dynamics.com
    private const string OrganizationRegion = "<your organization region>"; // might be crm for north america, check your dynamics login url    

    private string GetServiceUrl()
    {
        return $"{GetResourceUrl()}/XRMServices/2011/Organization.svc/web";
    }

    private string GetResourceUrl()
    {
        return $"https://{OrganizationName}.api.{OrganizationRegion}.dynamics.com";
    }

    private string GetAuthorityUrl()
    {
        return $"{LoginUrl}/{TenantId}";
    }

    public async Task<OrganizationWebProxyClient> CreateClient()
    {
        var context = new AuthenticationContext(GetAuthorityUrl(), false);
        var token = await context.AcquireTokenAsync(GetResourceUrl(), new ClientCredential(ClientId, ClientSecret));

        return new OrganizationWebProxyClient(new Uri(GetServiceUrl()), true)
        {
            HeaderToken = token.AccessToken,
            SdkClientVersion = "9.1"
        };
    }

    public async Task<OrganizationServiceContext> CreateContext()
    {
        var client = await CreateClient();
        return new OrganizationServiceContext(client);
    }

    public async Task TestApiCall()
    {
        var context = await CreateContext();

        // send a test request to verify authentication is working
        var response = (WhoAmIResponse) context.Execute(new WhoAmIRequest());
    }
}

暫無
暫無

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

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