【问题标题】:Youtube API C# OAuth token exchange for access_token returns invalid requestYoutube API C# OAuth 令牌交换 access_token 返回无效请求
【发布时间】:2013-11-16 18:53:36
【问题描述】:

我正在尝试对他的 Google 帐户中的用户进行身份验证,以访问和修改他的 Youtube 数据。 我设法从用户​​登录和条款接受中获得了返回的令牌,但是当我执行 POST 以将令牌交换为用户 access_token 时,它会在 Json 文件上返回一个“无效请求”。

这是我显示登录页面的方式:

string url = string.Format("https://accounts.google.com/o/oauth2/auth?client_id=XXXXXXX&redirect_uri=urn:ietf:wg:oauth:2.0:oob&scope=https://gdata.youtube.com&response_type=code&access_type=offline");
WBrowser.Navigate(new Uri(url).AbsoluteUri);

我使用HttpWebRequest 进行 POST

string url = "https://accounts.google.com/o/oauth2/token?code=XXXXXX&client_id=XXXXXXXXX&client_secret=XXXXXXXXX&redirect_uri=http://localhost/oauth2callback&grant_type=authorization_code";

HttpWebRequest httpWReq =  (HttpWebRequest)WebRequest.Create(url);

byte[] byteArray = Encoding.UTF8.GetBytes(url);

httpWReq.Method = "POST";
httpWReq.Host = "accounts.google.com";
httpWReq.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
httpWReq.ContentLength = byteArray.Length;

但它在这一行失败了:

HttpWebResponse myHttpWebResponse = (HttpWebResponse)httpWReq.GetResponse();

出现以下错误:

如果您设置 ContentLength>0 或 SendChunked==真。通过在之前调用 [Begin]GetRequestStream 来执行此操作 [开始]GetResponse。

然后我将我的 POST 请求更改为 TcpClient,如下所示:

TcpClient client = new TcpClient("accounts.google.com", 443);
Stream netStream = client.GetStream();
SslStream sslStream = new SslStream(netStream);
sslStream.AuthenticateAsClient("accounts.google.com");
{
    byte[] contentAsBytes = Encoding.ASCII.GetBytes(url.ToString());

    StringBuilder msg = new StringBuilder();
    msg.AppendLine("POST /o/oauth2/token HTTP/1.1");
    msg.AppendLine("Host: accounts.google.com");
    msg.AppendLine("Content-Type: application/x-www-form-urlencoded");
    msg.AppendLine("Content-Length: " + contentAsBytes.Length.ToString());
    msg.AppendLine("");
    Debug.WriteLine("Request");
    Debug.WriteLine(msg.ToString());
    Debug.WriteLine(url.ToString());

    byte[] headerAsBytes = Encoding.ASCII.GetBytes(msg.ToString());
    sslStream.Write(headerAsBytes);
    sslStream.Write(contentAsBytes);
}

Debug.WriteLine("Response");

StreamReader reader = new StreamReader(sslStream);
while(true) {  // Print the response line by line to the debug stream for inspection.
    string line = reader.ReadLine();
    if(line == null)
        break;
    Debug.WriteLine(line);
}

但在 JSon 文件中返回以下内容:

{
  "error" : "invalid_request"
}

我正在关注 Youtube API:https://developers.google.com/youtube/2.0/developers_guide_protocol_oauth2#OAuth2_Installed_Applications_Flow

您可以在这里测试 OAuth:https://developers.google.com/oauthplayground/

关于其他方法的任何建议,或者如何纠正我的问题?

【问题讨论】:

    标签: c# youtube-api oauth-2.0 google-oauth


    【解决方案1】:

    Uri 字符串和 HTTP 标头不是内容的一部分。因此,只需将 ContentLength 分配为零:

    httpWReq.ContentLength = 0;
    

    【讨论】:

    • 如果我这样做,当我尝试执行此操作时:HttpWebResponse myHttpWebResponse = (HttpWebResponse)httpWReq.GetResponse(); 抛出 System.Net.WebException:“远程服务器返回错误:(400) 错误请求。”
    【解决方案2】:

    您正在使用 ContentType = "application/x-www-form-urlencoded; charset=utf-8"; 进行 POST和内容长度,然后在 URL 中传递参数。

    来自 oauth 游乐场的简单复制/粘贴显示您的帖子应该是什么样子...

    POST /o/oauth2/token HTTP/1.1
    Host: accounts.google.com
    Content-length: 250
    content-type: application/x-www-form-urlencoded
    user-agent: google-oauth-playground
    
    code=4%2FfTu47TyLyXFg6eM2TcKv_ikQ1JJ1.kmu1bd6T8vsVXE-sT2ZLcbQH1fhchAI&redirect_uri=https%3A%2F%2Fdevelopers.google.com%2Foauthplayground&client_id=407408718192.apps.googleusercontent.com&scope=&client_secret=************&grant_type=authorization_code
    

    注意网址编码!

    另外,上次我尝试使用 localhost 作为重定向 URL 是不允许的。尝试在您的 etc/hosts 文件中将 localhost 映射到(例如)devserver.mydomain.com 并将其指定为您的重定向 URL。确保您还在 API 控制台中添加此内容。

    【讨论】:

    • 感谢@pinoyyid 的回答,它通过丢弃我的网址中的https://accounts.google.com/o/oauth2/token? 帮助我找到了问题的根源。
    【解决方案3】:

    我终于设法解决了这个问题。我最终使用了 TcpClient 版本,因为这是我第一次设法开始工作。所以最终的代码是这样的:

    string _clientID = HttpUtility.UrlEncode("XXXXXXXXXXX.apps.googleusercontent.com");
    string _clientSecret = HttpUtility.UrlEncode("XXXXXXXXXX");
    string _redirectUri = "urn:ietf:wg:oauth:2.0:oob";
    string _code = HttpUtility.UrlEncode(token);
    
    string url = "code=" + _code + "&client_id=" + _clientID + "&client_secret=" + _clientSecret + "&redirect_uri=" + _redirectUri + "&grant_type=authorization_code";
    
    TcpClient client = new TcpClient("accounts.google.com", 443);
    Stream netStream = client.GetStream();
    SslStream sslStream = new SslStream(netStream);
    sslStream.AuthenticateAsClient("accounts.google.com");
    {
        byte[] contentAsBytes = Encoding.ASCII.GetBytes(url.ToString());
        StringBuilder msg = new StringBuilder();
        msg.AppendLine("POST /o/oauth2/token HTTP/1.1");
        msg.AppendLine("Host: accounts.google.com");
        msg.AppendLine("Content-Type: application/x-www-form-urlencoded");
        msg.AppendLine("Content-Length: " + contentAsBytes.Length.ToString());
        msg.AppendLine("");
        Debug.WriteLine("Request");
        Debug.WriteLine(msg.ToString());
        Debug.WriteLine(url.ToString());
        byte[] headerAsBytes = Encoding.ASCII.GetBytes(msg.ToString());
        sslStream.Write(headerAsBytes);
        sslStream.Write(contentAsBytes);
    }
    Debug.WriteLine("Response");
    StreamReader reader = new StreamReader(sslStream);
    while(true) {  // Print the response line by line to the debug stream for inspection.
        string line = reader.ReadLine();
        if(line == null)
            break;
        Debug.WriteLine(line);
    }
    

    问题在于传递的 url,我不应该传递 https://accounts.google.com/o/oauth2/token?

    【讨论】:

    • 在你的代码中你写了:“string _code = HttpUtility.UrlEncode(token);”。 “令牌”变量是什么意思?如何计算?
    猜你喜欢
    • 2017-03-14
    • 2019-10-02
    • 1970-01-01
    • 2011-04-25
    • 2013-03-20
    • 1970-01-01
    • 1970-01-01
    • 2011-01-19
    • 1970-01-01
    相关资源
    最近更新 更多