-1

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);

}
Shawn
  • 45
  • 1
  • 11
  • What do you have so far – Charlieface Apr 10 '23 at 23:56
  • @Charlieface I'll check once I'm back in the office tomorrow and update the question with the code so far. Is that why this question got down-voted, do you think? I got a notification that someone had posted an answer as well, but they must have deleted it by the time I was able to check. – Shawn Apr 12 '23 at 00:19
  • Yeah waited a while and got no response. It's hard to advise you if we don't know what difficulty you are having beyond "the issue I am having with the grant_type". If you can show what difficulty you are having with `HttpClient` then this could be a much better question, with some sensible answers. The posted answer was just a code dump without any explanation, and was poorly written. – Charlieface Apr 14 '23 at 00:18
  • I apologize for the delay in my response, I had other more urgent things to attend to. I appreciate the feedback, and have updated the question, though I have since resolved the issue on my own. The issue was the body was string content, not form content, I understand why now. – Shawn Apr 15 '23 at 00:00
  • You should post the answer below, not as part of the question. You are welcome to answer your own question. – Charlieface Apr 15 '23 at 20:54

1 Answers1

0

I have since solved the issue on my own by changing the code as follows:

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 formData = new List<KeyValuePair<string, string>>

{

    new KeyValuePair<string, string>("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 FormUrlEncodedContent(body)

};

The issue was that the body was string content, not form content.

Shawn
  • 45
  • 1
  • 11