Google Open Auth 2.0 在服务器端获得access_token(错误请求错误、协议错误)

本文关键字:错误 token 请求 协议 access Auth Open 服务器端 Google | 更新日期: 2023-09-27 18:32:42

我正在尝试通过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.
        }
    }

此外,异常包含等于"协议错误"的状态。即使我尝试使用空参数字符串制作 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);

Google Open Auth 2.0 在服务器端获得access_token(错误请求错误、协议错误)

您的redirect_uri必须正确转义,否则您将获得格式错误的URL。

parameters["redirect_uri"] = Uri.EscapeDataString(_redirectUri);