0

从 Google 获得用于访问用户日历的授权代码后,我现在正尝试将其交换为访问令牌。根据他们自己的文档:

实际请求可能如下所示:

POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Content-Type: application/x-www-form-urlencoded

code=4/v6xr77ewYqhvHSyW6UJ1w7jKwAzu&
client_id=8819981768.apps.googleusercontent.com&
client_secret={client_secret}&
redirect_uri=https://oauth2-login-demo.appspot.com/code&
grant_type=authorization_code

我访问它的尝试如下(C#):

string url = "https://accounts.google.com/o/oauth2/token";
WebRequest request = HttpWebRequest.Create(url); 
request.Method = "POST"; 
request.ContentType = "application/x-www-form-urlencoded"; 

string body = "code=<the_code_I_received>&\r\n"
    + "client_id=<my_client_id>&\r\n"
    + "client_secret=<my_client_secret>&\r\n"
    + "redirect_uri=http://localhost:4300\r\n"
    + "grant_type=authorization_code&\r\n"
                            ;
byte[] bodyBytes = Encoding.ASCII.GetBytes(body); 
request.ContentLength = bodyBytes.Length ; 
Stream bodyStream = request.GetRequestStream(); 
bodyStream.Write(bodyBytes, 0, bodyBytes.Length); 
bodyStream.Close(); 

try 
{
    request.GetResponse(); 

'http://localhost:4300' 与我在原始请求中输入的完全一样(它是有效的,因为我通过在该端口上作为 Web 服务器侦听得到了代码),但我也尝试了只是 'http: //localhost'以防万一。

我尝试了一些建议,例如将代理设置为 null(无更改)和更改 Accept(不允许将该标头添加到 Web 请求)。

在每种情况下,我都会收到 HTTP 400 - 错误请求(try / catch 会触发一个异常说明)。

在 /token 后面加上一个斜杠(我会尝试任何事情!)导致 500 内部服务器错误,所以也不是这样。

知道我做错了什么吗?

4

1 回答 1

0

您需要正文中的新行 \r\n 吗?这段代码对我有用...

var req0 = WebRequest.Create("https://accounts.google.com/o/oauth2/token");
req0.Method = "POST";
string postData = string.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code",
code, //the code i got back
"2xxx61.apps.googleusercontent.com", "XJxxxFy",
"http://localhost:1599/home/oauth2callback"); //my return URI

byte[] byteArray = Encoding.UTF8.GetBytes(postData);
req0.ContentType = "application/x-www-form-urlencoded";
req0.ContentLength = byteArray.Length;
using (Stream dataStream = req0.GetRequestStream())
{
    dataStream.Write(byteArray, 0, byteArray.Length);
    dataStream.Close();
}
try
{
using (WebResponse response = req0.GetResponse())
    {
    using (var dataStream = response.GetResponseStream())
        {    
        using (StreamReader reader = new StreamReader(dataStream))
        {
         string responseFromServer = reader.ReadToEnd();
         var ser = new JavaScriptSerializer();
            accessToken = ser.DeserializeObject(responseFromServer);
        }
    }
}
}
catch (WebException wex){ var x = wex; }
catch (Exception ex){var x = ex;}
于 2012-04-04T17:25:10.217 回答