C# how to acquire OAuth2 Token using WebClient

117 Views Asked by At

How to get an OAuth2 access token using WebClient (.NET 3.5)?

I have already tried following code, but it fails ("Bad Request" error)

 using (var client = new WebClient())
        {
            var baseUri = String.Format("https://login.microsoftonline.com/{0}/oauth2/v2.0/token", tenantId);
            var params = String.Format("grant_type=client_credentials&scope=https://api.businesscentral.dynamics.com/.default&client_id={0}&client_secret={1}", clientId, clientSecret);
            client.Headers.Add("ContentType", "application/x-www-form-urlencoded");
            var responseToken = client.UploadString(baseUri, "POST", params);
            Console.Write(responseToken);
        }

.

using (var client = new WebClient())
        {
            var collection = new NameValueCollection();
            collection.Add("grant_type", "client_credentials");
            collection.Add("scope", "https://api.businesscentral.dynamics.com/.default");
            collection.Add("client_id", clientId);
            collection.Add("client_secret", clientSecret);

            var baseUri = String.Format("https://login.microsoftonline.com/{0}/oauth2/v2.0/token", tenantId);
            client.Headers.Add("ContentType", "application/x-www-form-urlencoded");
            var responseToken = client.UploadValues(baseUri, "POST", collection);
            Console.Write(responseToken);
        }
0

There are 0 best solutions below