验证 Azure Function App 以在线连接到 Dynamics 365 CRM [英] Authenticate Azure Function App to connect to Dynamics 365 CRM online

查看:18
本文介绍了验证 Azure Function App 以在线连接到 Dynamics 365 CRM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时您需要知道答案才能提出正确的问题,因此我不确定此查询的标题是否完美.反正就这样吧.

Sometimes you need to know the answer to ask the right question, so I'm not sure if the title of this query is perfect. Anyway here goes.

我开发了一个 Azure Function App(基于时间触发器)来在线连接到 Dynamics 365 并做一些工作.都好!由于这是一个 POC,我想看看有什么可能,所以我编写了以下代码.

I've developed an Azure Function App (time trigger based) to connect to Dynamics 365 online and do some work. All good! As this was a POC and I wanted to see what was possible, I wrote the following code.

        IServiceManagement<IOrganizationService> orgServiceManagement;
        orgServiceManagement = ServiceConfigurationFactory.CreateManagement<IOrganizationService>(new Uri(System.Environment.GetEnvironmentVariable("OrganizationService")));

        AuthenticationCredentials authCredentials = new AuthenticationCredentials();
        authCredentials.ClientCredentials.UserName.UserName = "[Non-interactive CRM Username here]";
        authCredentials.ClientCredentials.UserName.Password = "[Password here]";
        AuthenticationCredentials tokenCredentials;

        tokenCredentials = orgServiceManagement.Authenticate(authCredentials);

        OrganizationServiceProxy organizationProxy = new OrganizationServiceProxy(orgServiceManagement, tokenCredentials.SecurityTokenResponse);

我的问题......显然,现在 POC 工作了,我想找到一种方法来针对 Azure AD 对 Function App 进行身份验证(而不是在代码中传递凭据)并获得一个访问令牌,我可以使用它来创建我的 OrganisationServiceProxy,但我该怎么做呢.我似乎无法在那里找到一个直接的答案.许多架构师风格的答案都在云端.我需要开发人员风格的答案(先这样做,然后再这样做):)

My question... obviously now that the POC works I want to find a way to authenticate the Function App against Azure AD (instead of passing credentials in code) and get an access token that I can use to create my OrganisationServiceProxy, but how do I go about this. I cant seem to find a straight answer out there. Lots of architect-style answers that are way up in the clouds. I need developer-style answers (do this, then do that) :)

我相信很多新手 azure 开发人员会发现了解这一点很有用.提前致谢.

I'm sure a lot of newbie azure developers out there will find this useful to know. Thanks in advance.

编辑注意事项:此问题与 Authenticate 不同使用 Azure 函数中的 Dynamics 365,因为我在同一个租户和订阅中,使用时间触发器而不是 Web 挂钩.我的函数应用唤醒,连接到 CRM,进行一些计算,更新 CRM 并重新进入睡眠状态.

Note for editors: This question isn't the same as Authenticate with Dynamics 365 from an Azure Function as I'm in the same tenant and subscription, using time triggers and not web hooks. My function app wakes up, connects to CRM, does some calculations, updates CRM and goes back to sleep.

推荐答案

我已设法使用 Azure Key Vault 保护我的凭据.对于那些想要做同样事情的新手......这里是步骤.

I've managed to secure my credentials using the Azure Key Vault. For those newbies out there who are looking to do the same ... here are the steps.

  1. 登录到 azure 门户并创建一个密钥保管库,或者如果您已经拥有一个,则转到下一步.
  2. 创建密钥保管库后,请转到密钥保管库的机密部分.您现在将为需要保护的每个凭证创建一个秘密.就我而言,我为用户名创建了一个秘密,为密码创建了另一个.每次创建机密时,Azure 都会向您发出机密标识符.请记下这一点,因为稍后您将在 azure 函数配置设置中使用它.
  3. 接下来,您需要前往 Azure Active Directory (Azure AD).您需要前往应用注册并创建一个新的应用注册.此时,您是否创建了函数应用程序并不重要.此步骤只是通知 Azure AD 你有一个要注册的应用程序,以便它可以向你颁发应用程序 ID.在创建应用程序注册时,您需要记下发布的应用程序 ID.同样,您将在函数应用配置设置中使用它.
  4. 仍然在 Azure AD 中,应用注册单击密钥并创建一个新密钥.创建密钥后,Azure 将为您提供密钥值.(请记下此值,因为这是 Azure 唯一一次向您显示此值.)您在 azure 函数应用配置设置中也需要此应用密钥.
  5. 返回 Azure Key Vault 和您创建的 Key Vault.这次单击访问策略.您在此处所做的是允许您的 Azure AD 注册函数应用连接到此 Key Vault.点击 Add New,然后选择 principal,找到您在 Azure AD 中注册的应用程序(不要选择您的函数应用程序,它也会显示在此处,您需要选择与您在上面步骤 3 中在 Azure AD 中注册的名称相同的名称) 然后在秘密权限下,选择获取"并点击保存.
  6. 设置完成.其余的是代码更改以完成所有这些工作.
  7. 将以下 using 语句添加到代码顶部.

  1. Login to the azure portal and create a key vault or if you already have one then go to the next step.
  2. Once the key vault is created, go to the secrets section of the Key Vault. You will now create a secret for each credential you need to secure. In my case I created a secret for the username and another for the password. Each time you create a secret, azure will issue you with a secret identifier. Make note of this as you will be later using this in your azure function config settings.
  3. Next you need to head over to Azure Active Directory (Azure AD). You need to head to App Registrations and create a new app registration. It doesnt matter at this point if you created your function app or not. This step is just about informing Azure AD that you have an application that you want to register so that it can issue you with an application ID. On creation of the app registration, you will need to make note of the application ID issued. Again you will use this in your function app config settings.
  4. Still in Azure AD, app registrations click on Keys and create a new key. Once you create a key, azure will provide you with the key value. (Please make note of this value as this is the only time Azure will show you this value.) You will need this app key too in your azure function app config settings.
  5. Head back to Azure Key Vault and to the Key Vault you created. This time click on Access Policies. What you are doing here is allowing your Azure AD registered function app to connect to this Key Vault. Click on Add New, Then select principal, find the app your registered with Azure AD (Do not select your function app which will also display here, you need to select the same name that you registered with Azure AD in step 3 above) Then under secret permissions, select 'Get' and click Save.
  6. Thats the setup done. The rest are code changes to make all of this work.
  7. Add the following using statements to the top of your code.

使用 Microsoft.Azure.KeyVault;
使用 Microsoft.IdentityModel.Clients.ActiveDirectory;

using Microsoft.Azure.KeyVault;
using Microsoft.IdentityModel.Clients.ActiveDirectory;

如果您的函数应用代码位于 Azure 门户中,则将以下内容添加到您的 project.json 文件中.

If your function app code is in the Azure Portal, then add the following to your project.json file.

{构架": {net46":{依赖":{"Microsoft.IdentityModel.Clients.ActiveDirectory": "3.13.4","Microsoft.Azure.KeyVault": "2.0.1-preview","Microsoft.AspNet.WebApi.Client": "5.2.3",Microsoft.CrmSdk.CoreAssemblies":9.0.0.7"}}}}

{ "frameworks": { "net46": { "dependencies": { "Microsoft.IdentityModel.Clients.ActiveDirectory": "3.13.4", "Microsoft.Azure.KeyVault": "2.0.1-preview", "Microsoft.AspNet.WebApi.Client": "5.2.3", "Microsoft.CrmSdk.CoreAssemblies": "9.0.0.7" } } } }

如果您使用的是 Visual Studio,则需要确保将上述引用添加到您的项目中.

If you are using Visual Studio, then you will need to ensure that you add the above references to your project.

请参阅我上面的原始帖子,了解我如何在代码中使用凭据,以及我现在如何在下面的代码中更改它们.

Please see my original post above to see how I was using credentials in code to how I've changed them now in the code below.

AuthenticationCredentials authCredentials = new AuthenticationCredentials();authCredentials.ClientCredentials.UserName.UserName = GetKVSecret("Secret1", log);authCredentials.ClientCredentials.UserName.Password = GetKVSecret("Secret2", log);

AuthenticationCredentials authCredentials = new AuthenticationCredentials(); authCredentials.ClientCredentials.UserName.UserName = GetKVSecret("Secret1", log); authCredentials.ClientCredentials.UserName.Password = GetKVSecret("Secret2", log);

现在这里是 GetKVSecret 函数的代码.

And now here is the code for the GetKVSecret function.

private static string GetKVSecret(string secretName, TraceWriter log)
{
var adClientId = System.Environment.GetEnvironmentVariable("AppADClientID");
var adKey = System.Environment.GetEnvironmentVariable("AppADKey");
var secret = System.Environment.GetEnvironmentVariable(secretName);

var keyVault = new KeyVaultClient(async (string authority, string resource, string scope) => {
var authContext = new AuthenticationContext(authority);
var credential = new ClientCredential(adClientId, adKey);
var token = await authContext.AcquireTokenAsync(resource, credential); 
return token.AccessToken;
});
string returnValue;
try
{
    returnValue = keyVault.GetSecretAsync(secret).Result.Value;
    log.Info("Secret retrieved from Key Vault");
}
catch (Exception error)
{
    log.Error("Unable to get secrets from Azure Key Vault.", error);
    throw;
}
return returnValue;

}

最后一步,您可以看到我正在从配置中获取 AppADClientID 和 AppADKey.因此,您需要在应用设置屏幕中创建以下条目.
AppADClientID:您从第 3 步得到的值
AppADKey:你从第 4 步得到的值
secret1:你从第 2 步得到的值
secret2:你从第 2 步得到的值
secret1 和 2 可能会因您创建的 secret 数量而异.

Last step, you can see that I'm picking up the AppADClientID and AppADKey from the config. So you will need to create the following entries in your app settings screen.
AppADClientID: the value you got from step 3
AppADKey: the value you got from step 4
secret1: the value you got from step 2
secret2: the value you got from step 2
secret1 and 2 might vary depending on the number of secrets you created.

所以那里!我希望您觉得这很有用,如果您有任何疑问,请在此处发布,我会尽力回答.最后,我必须感谢以下帮助我的资源.

So there! I hope you find this useful and if you have any queries please post them here, I'll try my best to answer them. I have to end by giving credit to the following resources which helped me along the way.

链接 1链接 2

PS.这是一个用代码发布解决方案的皮塔饼.Stackoverflow 一直阻止我提交说我在窗口中的代码格式不正确.然而,我后来意识到这是与代码插入冲突的项目符号点上的自动"项目符号格式.不管怎样,我认为堆栈溢出不应该阻止一个帖子,因为它可能意味着内容提供者会沮丧地放弃(我们还有其他有偿工作要做!)

PS. This has been a pita to post the solution with code. Stackoverflow kept preventing me from submitting saying that I had code in the window that wasnt formatted correctly. However, I later realised it was the 'automatic' bullet formatting on the bullet points that was conflicting with the code inserts. Eitherway I think stack overflow should not prevent a post as it could mean content providers will give up in frustration (we have other paying jobs to do!)

这篇关于验证 Azure Function App 以在线连接到 Dynamics 365 CRM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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