访问令牌Google+

我在使用新发布的Google+ API检索访问令牌时遇到了一些问题…

我一直在关注文档 ,我得到了一个代码(“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 ... 

你忘记了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。 你也可以看到我的问题 ,我今天问了,后来解决了。

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

查看OAuth 2.0规范草案,并尝试完全按照Google的OAuth 2.0文档中的示例进行操作。 或者只使用附带OAuth 2.0支持的Google .NET库 。