对Azure Function应用进行身份验证以在线连接到Dynamics 365 CRM [英] Authenticate Azure Function App to connect to Dynamics 365 CRM online

查看:118
本文介绍了对Azure Function应用进行身份验证以在线连接到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.

编辑者注意:此问题与>验证与我位于同一租户和订阅中,通过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密钥保管库和您创建的密钥保管库.这次单击访问策略".您在这里所做的就是允许您的Azure AD注册功能应用程序连接到此Key Vault.单击添加新,然后选择主体,找到您在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 =新的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和secret2可能会有所不同,具体取决于您创建的机密数量.

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应用进行身份验证以在线连接到Dynamics 365 CRM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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