Pages

Friday 10 August 2018

OAuth authorization


Using Access tokens to connect with Dynamics 365


In this blog I am going to explain how we can connect to Dynamics 365 using Azure AD and OAuth
OAuth is the authentication method supported by the Dynamics 365 Customer Engagement Web API, and is one of two authentication methods for the Organization Service – the other being Active Directory authentication. One benefit of using OAuth is that your application can support multi-factor authentication. You can use OAuth authentication when your application connects to either the Organization service or the Discovery service.
Method calls to the web services must be authorized with the identity provider for that service endpoint. Authorization is approved when a valid OAuth 2.0 (user) access token, issued by Azure Active Directory, is provided in the headers of the message requests.

 The whole process can be summarized as below:
       1.       Register Dynamics 365 to Azure AD and get Client Id and Redirect URI
       2.       Use the above defined Client Id and URI to get Access Token
       3.       Using this Access Token to call Web API from CRM and get the desired result

Register Dynamics 365 to Azure AD


To start the process, we need our Dynamics 365 app to be registered with Azure AD. To register the app there, you can sign in to Azure management portal with your Microsoft account. You can also get there from Office 365 Admin center.
Follow below step to get your app registered:

Sign in to Azure Management Portal from Admin center.

a.       Login to office 365
b.       Go to Admin Center












c.       From left navigation pane select Azure Active Directory from Admin Centers




d.       You will be redirected to Azure Management Portal
e.       Select App Registration from Azure Active Directory on left bar and click on New Application Registration



f.        Enter Name ,Application Type(Native) and Redirect URI (http://localhost) and click Create


g.       You will now get Client Id (Application Id in App) to use in your authorization process

Use the Client Id and URI to get Access Token


Now we will use the Client ID and the URI we specified in App to get access token.

Create application to get data from CRM

        a.       Create a Console Application
        b.       Add Microsoft.IdentityModel.Client  package from NuGet to your current solution
       c.       Add following method to your application:
  public static async Task<string> GetAuthenticationTokenAsync(){
      
             string resource = "https://<orgname>.crm.dynamics.com";

            // TODO Substitute your app registration values that can be obtained after you 
            // register the app in Active Directory on the Microsoft Azure portal. 
             string clientId = "<client id>";
            string redirectUrl = "http://localhost";

            // Authenticate the registered application with Azure Active Directory. 
            AuthenticationContext authContext =
                new AuthenticationContext("https://login.windows.net/common", false);
            AuthenticationResult result = await authContext.AcquireTokenAsync(resource, clientId, new Uri(redirectUrl), new PlatformParameters(PromptBehavior.Auto));
          
            using (HttpClient httpClient = new HttpClient())
            {
                httpClient.BaseAddress = new Uri("https://<orgname>.api.crm.dynamics.com/");
                httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
                httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
                httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                //Set the Authorization header with the Access Token received specifying the Credentials
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);

//Get result
                HttpResponseMessage response = await httpClient.GetAsync("api/data/v9.0/accounts");
                string jsonString = await response.Content.ReadAsStringAsync();
                Console.Write(jsonString);
                Console.ReadKey();
            }
        d.       Run your application.
        e.       You will be redirected to Microsoft login page


       f.        Enter your Username and Password
       g.       You can see the requested data in console



Now you can access any entity using OAuth .

Happy CRMingJ
Preeti Sharma


No comments:

Post a Comment

Get or Update fields on form using JavaScript in Dynamics 365 v9

After Microsoft released v9.0 of Microsoft Dynamics 365, Xrm.page became deprecated that it have been replaced by ExecutionContext.getFor...