I have an Azure function that is working. However, I am trying to also use the azure function to do authentication to get access to Microsoft Dynamic CRM.
When trying to get my token is when my problem occurs.
I hope someone can help me get this working.
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);
}
}
}
Check below article and try to replicate the code provided on github repo. https://github.com/jlattimer/CrmWebApiCSharp/blob/master/CrmWebApiCSharp/Program.cs
I have tried this approach and it works.
Please mark my answer verified if i were helpful