我正在尝试通过 Google Open Auth 2.0 实现用户身份验证。我已经成功地从谷歌获得了“代码”,现在我正试图获得 access_token 来访问用户的信息。这是控制器的代码:
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”的状态。即使我尝试使用空参数字符串进行 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);