oauth2.0 从HttpWebRequest转换为HttpClient

6rqinv9w  于 2023-04-19  发布在  其他
关注(0)|答案(1)|浏览(171)

我正在使用Verizon ThingSpace API,在这里找到。
我正在尝试生成Oauth令牌。API文档提供了一个curl示例:

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"

我已经能够使用旧的HTTPWebRequest成功地复制C#中的curl命令,但使用新的HttpClient却失败了。
我得到一个返回值:

{"error":"invalid_request","error_description":"Invalid grant_type parameter or parameter missing"}

在C#中使用较新的HttpClient类复制API文档中的curl示例的正确方法是什么?我已经查看了this answer,但它没有解决我在grant_type中遇到的问题。
编辑:
下面是HTTPWebRequest实现,它按预期工作:

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

    }

}

下面是HttpClient实现,它不能正常工作:

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

}
cig3rfwq

cig3rfwq1#

我已经通过修改代码解决了这个问题,如下所示:

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)

};

问题是主体是字符串内容,而不是表单内容。

相关问题