OAuth2: The request body must contain the following parameter: 'grant_type'

173 views Asked by At

I am trying to get an accesstoken OAuth2 but I am getting this error:

'{"error":"invalid_request","error_description":"AADSTS900144: The request body must contain the following parameter: 'grant_type'. Trace ID: dd0ee743-c11e-48cc-b67f-91bd771a0500 Correlation ID: c7505426-844c-4dab-a2d9-9744a1af1b1a Timestamp: 2023-12-11 23:00:02Z","error_codes":[900144],"timestamp":"2023-12-11 23:00:02Z","trace_id":"dd0ee743-c11e-48cc-b67f-91bd771a0500","correlation_id":"c7505426-844c-4dab-a2d9-9744a1af1b1a","error_uri":"https://login.microsoftonline.com/error?code=900144"}'

Here is my code:

    HttpHeadersContent.TryAddWithoutValidation('Cache-Control', 'no-cache');
    HttpHeadersContent.Add('Ocp-Apim-Subscription-Key', SubKeyTest);
    HttpHeadersContent.TryAddWithoutValidation('Content-Type', 'application/x-www-form-urlencoded');
    HttpHeadersContent.Add('grant_type', 'client_credentials');
    HttpClient.DefaultRequestHeaders().Add('grant_type', 'client_credentials');
    HttpClient.DefaultRequestHeaders().Add('Ocp-Apim-Subscription-Key', SubKeyTest);
    HttpClient.DefaultRequestHeaders().Add('client_secret', ClientSecret);
    HttpContent.GetHeaders(HttpHeadersContent);

Is there something I am not doing right?

1

There are 1 answers

0
gaurav On

The error mentions that it expects the grant type in body instead of header. Probably as FormUrlEncodedContent. you can do something like this:

var dict = new Dictionary<string, string>
 {
 { "grant_type", "its value" }
};

var request = new HttpRequestMessage(HttpMethod.Post, "url");
request.Content = new FormUrlEncodedContent(dict);

// Rest of your code to send HttpRequest

You can add more items to dict if needed.