Friday, May 25, 2018

AggregateException was unhandled while connect to Dynamics 365 using OAuth

Recently  I was trying to connect to Dynamics 365 (v9.0) using OAuth, but was facing AggregateException


upon looking at the details of the exception I see its related to security




Once I placed below code, it started working fine

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

By the way here is the sample coe

namespace ConsoleApplication1 {
    class Program {
        static void Main(string[] args) {
            var execute = Task.Run(async () => await Auth());
            Task.WaitAll(execute);

        }

        public static async Task Auth() {

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

            var ap = await AuthenticationParameters.CreateFromResourceUrlAsync(
              new Uri("https://<<org>>.api.crm.dynamics.com/api/data/v9.0"));

            String authorityUrl = ap.Authority;
            String resourceUrl = ap.Resource;

            var authContext = new AuthenticationContext(authorityUrl);
            var clientCred = new ClientCredential("ApplicationID", "Key");
            var test = await authContext.AcquireTokenAsync(resourceUrl, clientCred);

            Console.WriteLine(test.AccessToken);

            using (var client = new HttpClient()) {
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", test.AccessToken);

                var response = await client.GetAsync("https://<<org>>.api.crm.dynamics.com/api/data/v9.0/contacts");
                var contacts = await response.Content.ReadAsStringAsync();

                Console.WriteLine(contacts);
            }
        }
        }
    }

AggregateException was unhandled while connect to Dynamics 365 using OAuth

Recently  I was trying to connect to Dynamics 365 (v9.0) using OAuth, but was facing AggregateException upon looking at the details ...