Issue
There is a code like this:
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
request.Headers.TryAddWithoutValidation("User-Agent", userAgent);
request.Content = new StringContent("{" +
$"\"grant_type\":\"authorization_code\"," +
$"\"client_id\":\"*****\"," +
$"\"client_secret\":\"****\"," +
$"\"code\":\"{autorizationCode}\"," +
$"\"redirect_uri\":\"urn:ietf:wg:oauth:2.0:oob\"" +
"}", Encoding.UTF8);
var response = await client.SendAsync(request);
Token = response.Content.ReadAsStringAsync().Result.ToString();
}
When I send a request, it gives me an error - "{"error":"invalid_request","error_description":"Missing required parameter: grant_type."}", but grant_type is present.
The request on the site looks like this:
curl -X POST "https://site/oauth/token" \
-H "User-Agent: APPLICATION_NAME" \
-F grant_type="authorization_code" \
-F client_id="CLIENT_ID" \
-F client_secret="CLIENT_SECRET" \
-F code="AUTORIZATION_CODE" \
-F redirect_uri="REDIRECT_URI"
Why is he giving this error? How can I fix it?
Solution
The CURL-Parameter -F
represents form content, not JSON-Content.
If you want to send FormContent, you cannot use StringContent
, you need to use FormUrlEncodedContent
, like this:
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
request.Headers.TryAddWithoutValidation("User-Agent", userAgent);
request.Content = new FormUrlEncodedContent( new List<KeyValuePair<string, string>>() {
new KeyValuePair<string,string>("grant_type", "authorization_code"),
new KeyValuePair<string,string>("client_id", "*****"),
new KeyValuePair<string,string>("client_secret", "*****"),
new KeyValuePair<string,string>("code", $"{autorizationCode}"),
new KeyValuePair<string,string>("redirect_uri", "urn:ietf:wg:oauth:2.0:oob")
} );
var response = await client.SendAsync(request);
Token = response.Content.ReadAsStringAsync().Result.ToString();
}
/Edit: Regarding your comment, your endpoint also supports JSON and you missed the content-type. I'll leave this here in case anyone gets into the problem with an exact CURL-Request like you mentioned.
Answered By - Compufreak