如何将服务器服务连接到Dynamics Online [英] How do I connect a server service to Dynamics Online

查看:100
本文介绍了如何将服务器服务连接到Dynamics Online的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在修改内部管理应用程序以连接到我们的在线托管Dynamics 2016实例。

I am modifying an internal management application to connect to our online hosted Dynamics 2016 instance.

在遵循一些在线教程之后,我一直在使用 Microsoft.Xrm.Sdk.Client 中> OrganizationServiceProxy 。

Following some online tutorials, I have been using an OrganizationServiceProxy out of Microsoft.Xrm.Sdk.Client from the SDK.

这似乎需要一个用户名和密码才能连接,这很好用,但是我想以某种方式连接,不需要特定用户的帐户详细信息。我认为我所见过的OAuth示例不适合,因为没有UI,也没有实际的人向其显示OAuth请求。

This seems to need a username and password to connect, which works fine, but I would like to connect in some way that doesn't require a particular user's account details. I don't think the OAuth examples I've seen are suitable, as there is no UI, and no actual person to show an OAuth request to.

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密钥?

Is there a way to connect with an application token or API key?

推荐答案

我发现要成功完成此操作,您需要设置以下所有内容:

I've found that to do this successfully, you'll need to setup all of the following:


  1. 在Azure AD中创建应用程序注册:


    • 授予它API动态权限,特别是作为组织用户访问Access Dynamics 365

    • 为其提供虚拟Web重定向URI,例如 http:// localhost / auth

    • 生成客户端机密并将其保存以供以后使用

对于第4步,您需要打开一个新的隐身模式窗口,构造au rl使用以下模式,然后在步骤2中使用您的用户帐户凭据登录:

For step 4, you'll want to open an new incognito window, construct a url using the following pattern and login using your user account credentials in step 2:

https://login.microsoftonline.com/<your租户ID> / oauth2 / authorize?client_id =<客户端ID>& response_type = code& redirect_uri =<从步骤1重定向uri>& response_mode = query& resource = https://<组织名称>。 < region> .dynamics.com& state =<随机值>

完成此操作后,您应该会看到Dynamics应用程序用户具有应用程序ID和应用程序ID URI。

When this is done, you should see that your Dynamics application user has an Application ID and Application ID URI.

现在使用ClientId和ClientSecret以及其他一些组织特定的变量,您可以通过Azure Active Directory(AAD)进行身份验证)以获取oauth令牌并构建 OrganizationWebProxyClient 。我还没有找到执行此操作的完整代码示例,但是出于个人目的,我开发了以下代码。请注意,您获取的令牌的有效期为1小时。

Now with your ClientId and ClientSecret, along with a few other organization specific variables, you can authenticate with Azure Active Directory (AAD) to acquire an oauth token and construct an OrganizationWebProxyClient. I've never found a complete code example of doing this, but I have developed the following for my own purposes. Note that the token you acquire has an expiry of 1 hr.

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());
    }
}

这篇关于如何将服务器服务连接到Dynamics Online的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆