我正在尝试对他的 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);
我用 aHttpWebRequest
来做 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==true,则必须提供请求正文。通过在 [Begin]GetResponse 之前调用 [Begin]GetRequestStream 来执行此操作。
然后,我将 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/
关于其他方法的任何建议,或者如何纠正我所拥有的?