As part of the blog series on using Power Platform as your Development Platform as a Service (DPaaS) here is the first blog post on how to authenticate your apps and services with Active Directory and Common Data Service

If you are looking to build apps or services that integrate with Power Platform and Common Data Service (CDS) you will of course have to authenticate your user(s) before being able to use any of the integration endpoints.

Authentication with Common Data Service is handled by Azure Active Directory and there are several options depending on your programming language and use case scenario.

This blog post discuss how to authenticate from JavaScript, Python and C#.

Read on for details on setting this up including sample code

Authentication in relation to Power Platform and Common Data Service (CDS) is handled via Azure Active Directory.

This makes authentication relatively simple as there are several official library available to support this in various programming languages

Before we get to the actual authentication there are a couple of prerequisites you need to have completed.

You need to create an Azure Active Directory App Registration that will be used in the authentication flow.


Creating an App Registration in Azure Active Directory

To create the App Registration follow these steps

  1. Sign in to the Azure portal on the tenant in which your CDS is provisioned.
  2. Navigate to Active Directory -> App Registrations
  3. Click New Registration
  4. Give your App Registration a Name and click Register
  5. From the Overview page of your newly created App Registration click API Permissions
  6. Click Add a permission and select Dynamics CRM (don't be confused by the name, the permissions are the same for accessing CDS)
  7. Select user_impersonation and click Add Permissions
  8. Click Grant admin consent button to grant the consent to using the API
  9. If you are using the App Registration in a Server to Server scenario click Certificates & secrets and create a new secret. Copy it to a place for safe keeping as you will not be able to read it once saved!
  10. If you plan on using this from a JavaScript client you should allow implicit flow. To do this click Manifest and set the oauth2AllowImplicitFlow to true

Now that we have our App Registration in place we need to allow it access to CDS. In order to do so we will create an Application User in CDS and give a security role that supports our use case scenario.


Creating an Application User in CDS

To create the Application User in CDS follow these steps

  1. Log in to and navigate to your environment
  2. Navigate to Settings -> Users + Permissions -> Users
  3. Change the view to Application Users and click New
  4. Give your use a user name, full name and email (does not have to be active unless you want your application user to send and receive emails)
  5. Paste in your Client Id from the App Registration you create in Azure Active Directory
  6. Click Save
  7. The application URI ID and the Azure AD Object ID should be filled in automatically once the Application User is saved.
  8. Now click Manage Roles and assign security role(s) appropriate for your use case scenario

Now you are ready to start writing code that integrate with CDS


CDS Integration Scenarios

There are two common scenarios for integrating with CDS

  1. Server to Server (S2S) authentication
    Authenticate your service using an application user in CDS. This means all requests to CDS will be in the context of the authenticated application user
  2. User authentication
    Authenticate the user accessing your app using the users credentials. With this approach all requests to CDS will be in the context of the authenticated user.


Server to Server, S2S, authentication

Depending on your programming language of choice you have a couple of options.

If you are developing you integrations in a .NET supported language I suggest you use the available .NET SDK to facilitate your authentication.

If you are developing you integration using the Web API endpoint you will have options depending on your programming language


Authenticated S2S using .NET SDK

If you are using the .NET SDK you should handle your authentication using the CrmServiceClient in the Microsoft.Xrm.Tooling.Connector namespace. Don't be confused by the CRM reference in the name, it perfectly supports Power Platform CDS instances as well as traditional Dynamics 365 CE instances.

The CrmServiceClient supports connection strings which are great because you can manage them in your configuration files and manipulate them in your build and release pipelines in order to ensure you code connects to the correct endpoint.

For S2S integration with CDS you have the option to authenticate via the Client and Secret principle which I will demonstrate below. There is also support to authenticate certificate thumbprint if you should need this.

Here is an example of authenticating your S2S integration using a connection string with CrmServiceClient and calling the WhoAmI() method to return the id of the authenticated user.

            //Connect to CDS

            string connectionString = ConfigurationManager.AppSettings["organizationUrl"].ToString(); ;

            CrmServiceClient conn = new CrmServiceClient(connectionString);

            IOrganizationService orgService = (IOrganizationService)conn.OrganizationWebProxyClient;

            //Get Id of current user

            WhoAmIResponse whoami = (WhoAmIResponse)orgService.Execute(new WhoAmIRequest());

            Guid userId = whoami.UserId;


Authenticated S2S using Web API

If you are integrating with CDS using the Web API you will need to handle the authentication process yourself by requesting an access token from Azure Active Directory. There are official libraries for a number of programming languages that can help you implement this.

Basically what you need to do is request an access token from the authority url for your tenant passing in the client id and secret together with the resource for which you are authenticating

The following C# code implements the GetAccessToken() method that authenticates with Active Directory and returns the access token

        private static async Task GetAccessToken()


            var appSettings = ConfigurationManager.AppSettings;

            String clientId = appSettings["clientId"];

            String secret = appSettings["secret"];

            String tenantId = appSettings["tenantId"];

            String resourceUrl = appSettings["resourceUrl"];

            var credentials = new ClientCredential(clientId, secret);

            var authContext = new AuthenticationContext("" + tenantId);

            var result = await authContext.AcquireTokenAsync(resourceUrl, credentials);

            return result.AccessToken;


Once you have the access token you must include it in an Authorization header in your request to the Web API

Here is an example of calling the WhoAmI() function using the access token returned by GetAccessToken()

        public static async Task GetCurrentUser()


            String accessToken = await GetAccessToken();

            var appSettings = ConfigurationManager.AppSettings;

            String apiUrl = appSettings["apiUrl"];

            HttpClient client = new HttpClient();

            HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Get, apiUrl + "WhoAmI()");

            message.Headers.Add("OData-MaxVersion", "4.0");

            message.Headers.Add("OData-Version", "4.0");

            message.Headers.Add("Prefer", "odata.include-annotations=*");

            message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

            var response = await client.SendAsync(message);

            return response;



User authentication

If you are building apps that will be accessing CDS in context of the user you must prompt the user to authenticate and use the returned access token your requests to CDS.

If using JavaScript to develop your app you can use the Adal.js library to handle authentication with Azure Active Directory.

The following example prompts the user to authenticate with username and password and MFA if required.

  // Function that manages authentication  

  function authenticate() {  

   //OAuth context  

   authContext = new AuthenticationContext(config);  

   // Check For & Handle Redirect From AAD After Login  

   var isCallback = authContext.isCallback(window.location.hash);  

   if (isCallback) {  



   var loginError = authContext.getLoginError();  

   if (isCallback && !loginError) {  

    window.location = authContext._getItem(authContext.CONSTANTS.STORAGE.LOGIN_REQUEST);  


   else {  

    errorMessage.textContent = loginError;  


   user = authContext.getCachedUser();  


 The config object passed to the AuthenticationContext constructor is similar to the configurations in the other examples

window.config = {  

   tenant: tenant,  

   clientId: clientId,  

   postLogoutRedirectUri: pageUrl,  

   endpoints: endpoints,  

   cacheLocation: 'localStorage', 



For full source code of the examples discussed here you can check the following repository on github:

Development Platform as a Service blog series

  1. Power Platform CDS for Apps - Development Platform as a Service - DPaaS 
  2. Authenticate your code with Azure Active Directory and Common Data Service, CDS - This blog post