访问令牌Google+

时间:2011-09-21 14:54:33

标签: c# api oauth google-api google-plus

我在新发布的Google+ API中遇到一些问题,无法检索访问令牌......

我一直关注documentation,我得到了一个代码(“4 / blablabla”)但是当我发送POST请求获取访问令牌时,我收到了“(400)错误请求”响应。 ..

这是我的代码:

// We have a request code, now we want an access token
StringBuilder authLink = new StringBuilder();
authLink.Append("https://accounts.google.com/o/oauth2/token");
authLink.AppendFormat("?code={0}", gplusCode);
authLink.AppendFormat("&client_id={0}", myClientId);
authLink.AppendFormat("&client_secret={0}", mySecret);
authLink.AppendFormat("&redirect_uri={0}", myRedirectUri);
authLink.Append("&scope=https://www.googleapis.com/auth/plus.me");
authLink.Append("&grant_type=authorization_code");

OAuthBase oAuth = new OAuthBase();
string normalizedUrl, normalizedRequestParameters;
string oAuthSignature = oAuth.GenerateSignature(new Uri(authLink.ToString()), appKey, appSecret, code, null, HttpMethod.POST.ToString(), oAuth.GenerateTimeStamp(), oAuth.GenerateNonce(), OAuthBase.SignatureTypes.HMACSHA1, out normalizedUrl, out normalizedRequestParameters);
oAuthSignature = oAuth.UrlEncode(oAuthSignature);

// Rebuild query url with authorization
string url = string.Format("{0}?{1}&oauth_signature={2}", normalizedUrl, normalizedRequestParameters, oAuthSignature);

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url.ToString());
request.Method = HttpMethod.POST.ToString();
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = 0;

// Send the request and get the response
try
{
    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    {
        // Do stuff ...

2 个答案:

答案 0 :(得分:2)

您忘记了POST请求。试试这个:

string url = "https://accounts.google.com/o/oauth2/token";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url.ToString());
request.Method = HttpMethod.POST.ToString();
request.ContentType = "application/x-www-form-urlencoded";

// You mus do the POST request before getting any response
UTF8Encoding utfenc = new UTF8Encoding();
byte[] bytes = utfenc.GetBytes(parameters); // parameters="code=...&client_id=...";
Stream os = null;
try // send the post
{
    webRequest.ContentLength = bytes.Length; // Count bytes to send
    os = webRequest.GetRequestStream();
    os.Write(bytes, 0, bytes.Length);        // Send it
}

try
{
    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    {
        // Do stuff ...

这将为您提供带有访问令牌的Json。你也可以看到my question,我今天问过,后来解决了。

答案 1 :(得分:1)

Google+ API uses OAuth 2.0用于授权。您似乎正在实施OAuth 2.0和OAuth 1.0的混合:您的代码为OAuth 2.0请求计算OAuth 1.0 oauth_signature,该请求在OAuth 2.0中已过时。

查看OAuth 2.0 specification draft并尝试完全按照Google's OAuth 2.0 documentation中的示例操作。或者只使用Google's .NET library  它支持OAuth 2.0。