D365 FO: Odata authentication (OAuth) via Code



using System;

using Microsoft.Azure.Storage.Blob;

using Microsoft.IdentityModel.Clients.ActiveDirectory;

using Newtonsoft.Json;

using Newtonsoft.Json.Linq;

using System.IO;

using System.Net.Http;

using System.Net.Http.Headers;

using System.Text;

using System.Threading;

using System.Threading.Tasks;

 

namespace FO_AuthTest

{

   

    internal class DMFManager

    {

 

        static string downloadUrl = string.Empty;

 

       

        static string aadTenant = "https://login.windows.net/test.com”;

       

        static string aadResource = "https://test-aos.cloudax.dynamics.com";

       

        static string aadClientAppId = "7671rt11-tggg-4287-b3a2-b67rt21123dd";

        static string aadClientAppSecret = "sfdsfsdfdsgfdsgfdsgfdg9LMrpVs4jWwRwpbOAs=";

 

    public static void Main(string[] args)

    {

        processTask();

    }

 

    /// <summary>

    /// Retrieves an authentication header from the service.

    /// </summary>

   /// <returns>The authentication header for the Web API call.</returns>

    private static string GetAuthenticationHeader()

    {

           AuthenticationContext authenticationContext = new AuthenticationContext(aadTenant);

            var credential = new ClientCredential(aadClientAppId, aadClientAppSecret);

            AuthenticationResult authenticationResult = authenticationContext.AcquireTokenAsync(aadResource,                                         credential).Result;

            return authenticationResult.AccessToken;

    }

 

    private static void processTask()

    {

                string authHeader = GetAuthenticationHeader(); //Get bearer token

                HttpClient client = new HttpClient();

                client.BaseAddress = new Uri(aadResource);

                client.DefaultRequestHeaders.Clear();

                client.DefaultRequestHeaders.Authorization = new      AuthenticationHeaderValue("Bearer", authHeader);

                ……..

                ……………

    }

 


1 comment:

  1. Such great information. Thanks for this article. very helpful. please keep share more article. ICV Certification

    ReplyDelete

Powered by Blogger.