top of page
Search
  • bouhmidiasmaa

Authentication to Dataverse using Azure Function v3 (.NET core) & Azure Key Vault


In many cases you find yourself obliged to use Azure Function to connect to your Dataverse and perform certain actions, in this post i will try to present the necessary steps to create and connect an Azure Function to your Dataverse using Azure Key Vault to secure the connection information.

  1. First thing to do, create an App Registration in Azure:


add Dynamics Crm in the Api Permission.


and create an application user for this app in your environment in Admin Power Platform giving him the System Administration security role and the created app.


2. Then create a Function App in Azure, and select the ".Net" as the Runtime stack and "3.1" as the Version.


3. Now lets configure the information to connect to Dataverse in Azure key Vault.

create Azure Key Vault in Azure.


once created go to your resource and add Secrets.


we will add three secrets, the organisation URL of our Dataverse environment, the client Id and client secret from the App Registration created in the first step.

- Organisation Url is something as follow : https://OrganisationName.crm4.dynamics.com/, you can get the organization name from the Admin Power Platform center.


- Client Id : is the Application (client) ID from the App Registration.

- Client Secret : is the Client Secret Value (not the Id) from the Certificates and Secrets section in your App Registration, you should copy the value when creating the client secret, the value will not be visible after refreshing the page so make sure to save the value after creating the secret.

once collection the three value return to the azure key vault an create those secrets.


to authorize the access to the secrets created in your Key Vault from the Function App, add an Access Policy in key vault to the function app, and set the Secret Permissions to Get and List.



and click on Add.

4. Return to the Function App created and add application settings variables where you will get those secrets in the Configuration section in your Function App using the following expression:

@Microsoft.KeyVault(SecretUri={theSecretUri})

you can get the secret Uri from azure key vault (each secret will have it's own Uri)

repeat this action for the three secrets.

do not forget to enable Identity on your function otherwise you will not be able to get the values of your secrets from key vault.

once you finish you will see that application settings created in your azure function are marked in green which mean the configuration is correct.


5. Now lets create our Azure Function in Visual Studio.

open Visual Studio (I'm working with Visual Studio 2019), and select Azure Function.


click next then select ".Net Core 3" as the runtime and Http trigger as the trigger, and click create.


the function will look as follow.


to connect to Dataverse you need to install the following 2 NuGets:

  1. Microsoft.Powerform.Dataverse.Client

  2. Microsoft.Powerform.Dataverse.Client.Dynamics

use the following code to connect to your Dataverse (In this example I have retrieved the names of the contacts in my environments)

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Microsoft.PowerPlatform.Dataverse.Client;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk;
using System.Collections.Generic;

namespace DemoAzureFunction
{
    public static class DemoAzureFunctionDataverse
    {
        [FunctionName("DemoAzureFunctionDataverse")]
        public static void Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            //Get Environment Variable from Azure Function App's Application settings

            var clientId = Environment.GetEnvironmentVariable("ClientId");
            var clientSecret = Environment.GetEnvironmentVariable("ClientSecret");
            var organizationUrl = Environment.GetEnvironmentVariable("OrganizationUrl");

            //Build the Connection string
            string connectionString = $"Url={organizationUrl};ClientId={clientId};ClientSecret={ clientSecret};AuthType =ClientSecret";
             
            //Connect to Dataverse 
            ServiceClient service = new ServiceClient(connectionString);

            if (!service.IsReady)
            {
                throw new Exception("Authentication Failed!");
            }

            //get names of all the Contacts in our Dataverse 
            QueryExpression query = new QueryExpression("contact");
            query.ColumnSet = new ColumnSet("firstname", "lastname"); // true : return all columns
            var contacts = service.RetrieveMultiple(query).Entities;
            foreach (Entity contact in contacts)
            {
                string firstname = contact.Attributes.Contains("firstname") ? contact.GetAttributeValue<string>("firstname") : "";
                string lastname = contact.Attributes.Contains("lastname") ? contact.GetAttributeValue<string>("lastname") : "";
                log.LogInformation("contact : " + firstname + " " + lastname);
            }

        }
    }
}

publish the function, and test it in Azure Portal.





and now you can add your own actions :)

0 comments
bottom of page