[英]Google Open Auth 2.0 gain access_token on server side (Bad Request error, ProtocolError)
I'm trying to implement user Authentication via Google Open Auth 2.0. 我正在尝试通过Google Open Auth 2.0实现用户身份验证。 I've already succeed to gain "code" from Google and now I'm trying to gain access_token to access users' info.
我已经成功地从Google获得了“代码”,现在我正试图获得access_token来访问用户的信息。 This is code of the controller:
这是控制器的代码:
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.
}
}
Also the exception contains Status that equals "ProtocolError". 此外,异常中包含的状态等于“ ProtocolError”。 I have the same error even if I try to make POST with empty parametersString.
即使我尝试使用空的parametersString进行POST,我也会遇到相同的错误。
I'll appreciate any advice or suggestion. 我将不胜感激任何意见或建议。
Thanks 谢谢
Edit: I also tried this snippet both with and without parameters(have the same error): 编辑:我也尝试了带有和不带参数的此代码段(具有相同的错误):
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);
您的redirect_uri必须正确转义,否则您将获得格式错误的URL。
parameters["redirect_uri"] = Uri.EscapeDataString(_redirectUri);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.