I am working with the Verizon ThingSpace api, found here.
I am attempting to generate the Oauth token. The API documentation provides a curl example:
curl -X POST -d "grant_type=client_credentials" -H "Authorization: Basic BASE64_ENCODED_APP_KEY_AND_SECRET" -H "Content-Type: application/x-www-form-urlencoded" "/api/ts/v1/oauth2/token"
I have been able to successfully replicate the curl command in C# using the older HTTPWebRequest, but have failed to do so using the newer HttpClient.
I get a return value of:
{"error":"invalid_request","error_description":"Invalid grant_type parameter or parameter missing"}
What is the proper way of replicating the curl example in the API docs using the newer HttpClient class in c#? I have reviewed this answer, but it doesn't address the issue I am having with the grant_type.
Edit:
Here is the HTTPWebRequest implementation, which is working as expected:
public static void API_Login()
{
Console.WriteLine("API Request ----------------------------------");
string url = @https://thingspace.verizon.com/api/ts/v1/oauth2/token;
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Headers.Add("Authorization", $"Basic {encodedKeyAndSecret}");
var body = "grant_type=client_credentials";
var data = Encoding.ASCII.GetBytes(body);
httpWebRequest.ContentLength = data.Length;
using (var stream = httpWebRequest.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
JsonObject jsonObject = (JsonObject)JsonObject.Parse(result);
apiToken = jsonObject["access_token"].ToString();
}
}
And here is HttpClient implementation, which is not working correctly:
public async static void HttpClient_API_Login(string encodedKeyAndSecret)
{
string url = @https://thingspace.verizon.com/api/ts/v1/oauth2/token;
var client = new HttpClient();
var body = "grant_type=client_credentials";
var request = new HttpRequestMessage()
{
Method = HttpMethod.Post,
RequestUri = new Uri(url),
Headers =
{
{ HttpRequestHeader.ContentType.ToString(), $"application/x-www-form-urlencoded" },
{ HttpRequestHeader.Authorization.ToString(), $"Basic {encodedKeyAndSecret}" },
},
Content = new StringContent(body)
};
var response = client.SendAsync(request).Result;
var sr = await response.Content.ReadAsStringAsync();
Console.WriteLine("response: " + sr);
}