Error 400 requesting Auth Token from the server

Agresta Cristian 0 Reputation points
2023-02-24T11:42:35.13+00:00

I have to request the OAuth2 token to access to Office365.

I registred my app on AAD, get the client secret and so on, and I create a simple test to verify if it worlks. And it works. But when I try to run the same application from the server, i get error 400!

Can you help me to fix it?

I try also with https://developer.microsoft.com/en-us/graph and postman, and the data are correct.

The code:

        public static string GetAccessToken() 
        {

            string tenantId = "xxx"; 
            string clientId = "yyy";
            string clientSecret = "zzz";            
            string grant_type = "client_credentials";
            string scope = "https://graph.microsoft.com/.default";

            var uri = string.Format("https://login.microsoftonline.com/{0}/oauth2/v2.0/token", tenantId);
            var postData = string.Format("client_id={0}&client_secret={1}&grant_type={2}&scope={3}", clientId, clientSecret, grant_type, scope);
            var request = (HttpWebRequest)WebRequest.Create(uri); 
            
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            using (var streamWriter = new StreamWriter(request.GetRequestStream()))
            {
                streamWriter.Write(postData);
                streamWriter.Flush();
            }

            var response = (HttpWebResponse)request.GetResponse();  <---- Here I get the errpr
            var responseStream = response.GetResponseStream();
            var responseString = new StreamReader(responseStream).ReadToEnd();
            
            tokenResponse tResponse = JsonConvert.DeserializeObject
Microsoft Security Microsoft Entra Microsoft Entra ID
Microsoft Security Microsoft Graph
Developer technologies C#
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. P a u l 10,761 Reputation points
    2023-02-24T12:24:14.0166667+00:00

    The /token endpoint returns a payload to help you figure out what part of the request it didn't like:

    https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow#error-response-1

    WebRequest is an older API for doing HTTP requests - the standard approach for modern C# is to use HttpClient, which by default doesn't throw when the server returns a non-success HTTP status code, which is handy if you're trying to read the response body of a failed request:

    https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=net-7.0

    https://learn.microsoft.com/en-us/dotnet/api/system.net.httpwebrequest.getresponse?view=net-7.0#remarks

    But if need to use WebRequest you'll need to wrap your .GetResponse() line in a try/catch:

    try {
        // ...
        var response = (HttpWebResponse)request.GetResponse();
        // ...
    } catch (WebException ex) {
        Console.WriteLine(ex.Status);
        Console.WriteLine(ex.Response);
    }
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.