0

我想使用谷歌的 OAUTH2.0 对访问我网站的用户进行身份验证。

我已成功获得授权代码作为响应,现在当我在获取访问令牌时向 Google 发出“POST 请求”时遇到问题。问题是随着时间的推移请求仍在继续,我没有得到任何回应。

我在下面写的代码有什么问题吗?

StringBuilder postData = new StringBuilder();
postData.Append("code=" + Request.QueryString["code"]);
postData.Append("&client_id=123029216828.apps.googleusercontent.com");
postData.Append("&client_secret=zd5dYB9MXO4C5vgBOYRC89K4");
postData.Append("&redirect_uri=http://localhost:4180/GAuth.aspx&grant_type=authorization_code");

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token?code=" + Request.QueryString["code"] + "&client_id=124545459218.apps.googleusercontent.com&client_secret={zfsgdYB9MXO4C5vgBOYRC89K4}&redirect_uri=http://localhost:4180/GAuth.aspx&grant_type=authorization_code");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
string addons = "/o/oauth2/token?code=" + Request.QueryString["code"] + "&client_id=123029216828.apps.googleusercontent.com&client_secret={zd5dYB9MXO4C5vgBOYRC89K4}&redirect_uri=http://localhost:4180/GAuth.aspx&grant_type=authorization_code";

request.ContentLength = addons.Length;

Stream str = request.GetResponse().GetResponseStream();
StreamReader r = new StreamReader(str);
string a = r.ReadToEnd();

str.Close();
r.Close();
4

1 回答 1

2

正如我在评论中提到的,您的代码中只有一些小错误。就目前而言,您实际上并没有发布任何内容。我假设您打算发送postData字符串。

以下应该有效:

//Build up your post string
StringBuilder postData = new StringBuilder();
postData.Append("code=" + Request.QueryString["code"]);
postData.Append("&client_id=123029216828.apps.googleusercontent.com");
postData.Append("&client_secret=zd5dYB9MXO4C5vgBOYRC89K4");
postData.Append("&redirect_uri=http://localhost:4180/GAuth.aspx&grant_type=authorization_code");

//Create a POST WebRequest
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token?code=" + Request.QueryString["code"] + "&client_id=124545459218.apps.googleusercontent.com&client_secret={zfsgdYB9MXO4C5vgBOYRC89K4}&redirect_uri=http://localhost:4180/GAuth.aspx&grant_type=authorization_code");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";

//Write your post string to the body of the POST WebRequest
var sw = new StreamWriter(request.GetRequestStream());
sw.Write(postData.ToString());
sw.Close();

//Get the response and read it
var response = request.GetResponse();
var raw_result_as_string = (new StreamReader(response.GetResponseStream())).ReadToEnd();

您只是缺少将字符串附加到 POST WebRequest 的部分。

于 2013-02-23T07:09:06.340 回答