Xamarin 中对 oAuth2 Keycloak 服务器 return me 400 'Bad Request' 的 HTTPS 请求

HTTPS request to a oAuth2 Keycloak server return me 400 'Bad Request' in Xamarin

我正在翻译适用于 C#(Xamarin 应用程序)的 javascript 代码。我从服务器 400 'Bad Request'

取回

我想知道我用 C# 写的代码是否正确,或者我遗漏了什么。

JS代码:

function requestTokens(code) {
    var codeVerifier = document.getElementById("codeVerifierValue").innerHTML;
    var data = {
        "grant_type": "authorization_code",
        "client_id": "clientid",
        "code": code,
        "code_verifier": codeVerifier,
        "redirect_uri": "https://redirectUrl"
    };
    $.ajax({
        beforeSend: function (request) {
            request.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
        },
        url: "https://myUrl",
        data: data,
        success: responseFromPostRequest,
        dataType: "json"
    });
}

C#代码:

private HttpClient _httpClient = new HttpClient();

private async Task<string> HttpPost(string url, DataDto data)
{
    var jsonData = JsonConvert.SerializeObject(data);
    var content = new StringContent(jsonData, Encoding.UTF8, "application/x-www-form-urlencoded");

    var response = await _httpClient.PostAsync(new Uri(url), content);
}

感谢您的帮助

已更新日志响应:

{StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  Cache-Control: no-store
  Connection: keep-alive
  Date: Wed, 10 Nov 2021 17:37:43 GMT
  Pragma: no-cache
  Referrer-Policy: no-referrer
  Strict-Transport-Security: max-age=31536000; includeSubDomains
  X-Android-Received-Millis: 1636565866035
  X-Android-Response-Source: NETWORK 400
  X-Android-Selected-Protocol: http/1.1
  X-Android-Sent-Millis: 1636565857210
  X-Content-Type-Options: nosniff
  X-Frame-Options: SAMEORIGIN
  X-XSS-Protection: 1; mode=block
  Content-Length: 84
  Content-Type: application/json
}}

所以我发现在 Content-type application/x-www-form-urlencoded 的情况下,它不应该是要粘贴到 post 请求中的 JSON 文件。

我找到了截取的代码:

public static async Task<TResult> PostFormUrlEncoded<TResult>(string url, IEnumerable<KeyValuePair<string, string>> postData)
{
    using (var httpClient = new HttpClient())
    {
        using (var content = new FormUrlEncodedContent(postData))
        {
            content.Headers.Clear();
            content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

            HttpResponseMessage response = await httpClient.PostAsync(url, content);

            return await response.Content.ReadAsAsync<TResult>();
        }
    }
}

有了这个就完美了