Google Open Auth 2.0 gain access_token on server s

2019-06-13 19:57发布

问题:

I'm trying to implement user Authentication via 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. 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". I have the same error even if I try to make POST with empty parametersString.

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);

回答1:

Your redirect_uri has to be escaped correctly, otherwise you get a malformed URL.

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