使用应用程序服务并可以在线访问Microsoft Dynamic 365 CRM的天蓝色功能

问题描述

我有一个正在运行的Azure功能。但是,我也尝试使用azure函数进行身份验证以访问Microsoft Dynamic CRM。

当我遇到问题时尝试获取令牌。

我希望有人能帮助我完成这项工作。

using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.WebServiceClient;

namespace LanguageFunction
{
    public static class LanguageFunctionPlugin
    {

       [FunctionName("LanguageFunctionPlugin")]
       public static async Task<HttpResponseMessage> 
Run([HttpTrigger(AuthorizationLevel.Function,"get","post",Route = null)]HttpRequestMessage req,TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");

            // parse query parameter
           string name = req.GetQueryNameValuePairs()
               .FirstOrDefault(q => string.Compare(q.Key,"name",true) == 0)
               .Value;


            string organizationUrl = "https://xxxxxx.crm.dynamics.com";
            string api = "https://xxxxxx.crm.dynamics.com/api/data/v9.1";

            AuthenticationParameters ap = AuthenticationParameters.CreateFromUrlAsync(
                new Uri(api)).Result;

            var clientId = "833ab393-56ef-6ed6-10e7-89accb8fea8b";
            var secertKey = ".N:?.h6NfT3FVCNcfdvzfbZzPZguq6t3";

            var creds = new ClientCredential(clientId,secertKey);
            log.Info("client:" + clientId);

            AuthenticationContext authContext = new AuthenticationContext(ap.Authority);
            var token = authContext.AcquiretokenAsync(ap.Resource,creds).Result.Accesstoken;

            log.Info("Token : " + token);

            Uri serviceUrl = new Uri(organizationUrl + @"/xrmservices/2011/organization.svc/web?SdkClientVersion=v9.1");

            using (var sdkService = new OrganizationWebProxyClient(serviceUrl,false))
            {
                sdkService.HeaderToken = token;

                var _orgService = (IOrganizationService)sdkService != null ? (IOrganizationService)sdkService : null;
                log.Info("Get Org Service");
            }

            return name == null
                ? req.CreateResponse(HttpStatusCode.BadRequest,"Please pass a name on the query string or in the request body")
                : req.CreateResponse(HttpStatusCode.OK,"Hello " + name);
        }
   }

}

解决方法

检查以下文章,并尝试复制github repo提供的代码。 https://github.com/jlattimer/CrmWebApiCSharp/blob/master/CrmWebApiCSharp/Program.cs

我已经尝试过这种方法,并且有效。

如果我有帮助,请标记为我的答案