【问题标题】:Twitter api, failed to get access_token by 2/oauth/token with PKCETwitter api,无法使用 PKCE 通过 2/oauth/token 获取 access_token
【发布时间】:2022-08-12 20:58:15
【问题描述】:

我想使用带有 C# 的 twitter api 制作桌面应用程序。

在如何与 PKCE 连接之后,我已成功通过 i/oauth2/authorize api 获取授权代码。 https://developer.twitter.com/en/docs/authentication/oauth-2-0/user-access-token

但是 step3, 2/oauth2/token 总是返回错误。 错误是“invalid_request”和“为令牌传递的值无效。”

有人知道我的代码有错误吗?

using System.Diagnostics;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Web;

public async Task Authorize()
{
    var state = GenerateRandomString(inLength: 200);
    var codeVerifier = GenerateRandomString(inLength: 100);
    var challenge = codeVerifier;
    //var challenge = GenerateCodeS256Challenge(codeVerifier);
    var challengeMethod = \"plain\";
    var scope = \"tweet.read tweet.write users.read offline.access\".Replace(\" \", \"%20\");

    var url = \"https://twitter.com/i/oauth2/authorize\";
    url = $\"{url}?response_type=code&client_id={ClientID}&redirect_uri={RedirectUrl}&scope={scope}&state={state}&code_challenge={challenge}&code_challenge_method={challengeMethod}\";

    var http = new HttpListener();
    http.Prefixes.Add(RedirectUrl);
    http.Start();

    Process.Start(new ProcessStartInfo
    {
        FileName = url,
        UseShellExecute = true,
    });

    var context = await http.GetContextAsync();
    var httpResponse = context.Response;
    var buffer = Encoding.UTF8.GetBytes(\"<html><body>Please return to the app.</body></html>\");
    httpResponse.ContentLength64 = buffer.Length;
    var responseOutput = httpResponse.OutputStream;
    await responseOutput.WriteAsync(buffer, 0, buffer.Length);
    responseOutput.Close();
    http.Stop();

    if (context.Request.QueryString.Get(\"state\") == state)
    {
        var code = context.Request.QueryString.Get(\"code\");

        var request = new HttpRequestMessage(HttpMethod.Post, \"https://api.twitter.com/2/oauth2/token\");
        //request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(
        //        \"Basic\",
        //        Convert.ToBase64String(Encoding.ASCII.GetBytes($\"{ClientID}:{ClientSecret}\"))
        //    );
        request.Content = new FormUrlEncodedContent(new Dictionary<string, string>
        {
            { \"code\", code },
            { \"grant_type\", \"authorization_code\" },
            { \"client_id\", ClientID },
            { \"redirect_url\", RedirectUrl},
            { \"code_verifier\", codeVerifier },
        });

        // status code: 400, Bad Request
        var response = await _httpClient.SendAsync(request);
        // {
        //      \"error\":\"invalid_request\",
        //      \"error_description\":\"Value passed for the token was invalid.\"
        // }
        var json = await response.Content.ReadAsStringAsync();
    }
}

    标签: c# twitter twitter-oauth


    【解决方案1】:

    在 ms-dos 终端上尝试 curl 命令,成功获得令牌响应。

    现在,我制作调用 curl 命令的 bat 文件,然后运行该文件并读取输出。

    oauth2_token.bat:

    @set CODE=%1
    @set CLIENT_ID=%2
    @set REDIRECT_URL=%3
    @set CODE_VERIFIER=%4
    
    @curl --location --request POST https://api.twitter.com/2/oauth2/token --header 'Content-Type: application/x-www-form-urlencoded' --data-urlencode "code=%CODE%" --data-urlencode "grant_type=authorization_code" --data-urlencode "client_id=%CLIENT_ID%" --data-urlencode "redirect_uri=%REDIRECT_URL%" --data-urlencode "code_verifier=%CODE_VERIFIER%"
    

    C#代码:

    var psInfo = new ProcessStartInfo();
    psInfo.FileName = "oauth2_token.bat";
    psInfo.Arguments = $"{code} {inClientID} {inRedirectUrl} {codeVerifier}";
    psInfo.CreateNoWindow = true;
    psInfo.UseShellExecute = false;
    psInfo.RedirectStandardOutput = true;
                
    var process = Process.Start(psInfo)!;
    
    var json = "";
    while ((json = process.StandardOutput.ReadLine()) != null)
    {
        break;
    }
    var deserialized = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
    var bearerToken = deserialized["access_token"];
    

    我还不知道为什么我的第一个代码失败了。

    【讨论】:

      猜你喜欢
      • 2022-11-11
      • 2012-06-07
      • 2012-06-03
      • 1970-01-01
      • 2013-07-10
      • 1970-01-01
      • 2015-03-31
      • 2012-03-08
      • 2015-12-19
      相关资源
      最近更新 更多