0
我试图通过Google Open Auth 2.0实现用户身份验证。我已经成功地从Google获得“代码”,现在我试图通过access_token访问用户的信息。这是控制器的代码:Google Open Auth 2.0获得服务器端的access_token(错误请求错误,ProtocolError)
public void Google(string code)
{
if (!string.IsNullOrWhiteSpace(code))
{
var parameters = new Dictionary<string, string>();
parameters["code"] = code;
parameters["client_id"] = ConfigurationProvider.GoogleApplicationId;
parameters["client_secret"] = ConfigurationProvider.GoogleClientSecret;
parameters["redirect_uri"] = "http://localhost:1291" + Url.Action("GoogleAuth");
parameters["grant_type"] = "authorization_code";
var keyValuePairs = new string[parameters.Count];
var i = 0;
const string keyValueTemplate = "{0}={1}";
foreach (var parameter in parameters)
{
keyValuePairs[i] = string.Format(keyValueTemplate, parameter.Key, parameter.Value);
i++;
}
var parametersString = string.Join("&", keyValuePairs);
// code=CODE&client_id=MY.apps.googleusercontent.com&client_secret=SECRET&redirect_uri=http://localhost:1291/Account/GoogleAuth&grant_type=authorization_code
const string uri = "https://accounts.google.com/o/oauth2/token";
var webClient = new WebClient();
webClient.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
webClient.UploadString(uri, "POST", parametersString); // Here I get Bad Request exception.
}
}
此外,该例外包含等于“ProtocolError”的Status。即使我尝试使用空的parametersString进行POST,我也有同样的错误。
我会感谢您的任何建议或建议。
感谢
编辑: 我也尝试过这个片段既没有参数(具有相同的错误):
var data = new NameValueCollection
{
{"code", code},
{"client_id", ConfigurationProvider.GoogleApplicationId},
{"client_secret", ConfigurationProvider.GoogleClientSecret},
{"redirect_uri", "http://localhost:1291" + Url.Action("GoogleAuth")},
{"grant_type", "authorization_code"}
};
var webClient = new WebClient();
webClient.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; // with and without this header...
var result = webClient.UploadValues(uri, "POST", data);
看来这是请求编码(UTF-8,ASCII等)的问题。不过,我以非常不同的方式解决了这个问题=)谢谢你的答案。 – 2012-07-08 07:11:32