.Net Google OAuth token WebRequest Bad Request Pro

2019-07-26 10:30发布

问题:

I'm doing fine with this OAuth2 stuff until I try to get the token.

I think I'm doing something to do with the encoding.

Here is my code:

string url = "https://accounts.google.com/o/oauth2/token";

StringBuilder postDataBuider = new StringBuilder();
postDataBuider.AppendLine("code=" + code);
postDataBuider.AppendLine("client_id=" + System.Configuration.ConfigurationManager.AppSettings["GoogleApplicationClientId"].ToString());
postDataBuider.AppendLine("client_secret=" + System.Configuration.ConfigurationManager.AppSettings["GoogleApplicationClientSecret"].ToString());
postDataBuider.AppendLine("redirect_uri=" + System.Configuration.ConfigurationManager.AppSettings["AppDomain"] + "Account/YouTubeOAuth2Callback");
postDataBuider.AppendLine("grant_type=authorization_code");

string postDataStr = postDataBuider.ToString();
// byte[] postDataBytes = System.Text.Encoding.GetEncoding("application/x-www-form-urlencoded").GetBytes(postDataStr);
byte[] postDataBytes = System.Text.Encoding.UTF8.GetBytes(postDataStr);

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Accept = "application/json";
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postDataBytes.Length;

Stream dataStream = request.GetRequestStream();
dataStream.Write(postDataBytes, 0, postDataBytes.Length);
dataStream.Close();

string responseStr = "";

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
    using (Stream responseStream = response.GetResponseStream())
    {
        using (StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8))
        {
            responseStr = readStream.ReadToEnd();

            if (String.IsNullOrWhiteSpace(responseStr))
            {
                throw new Exception("Response is null or empty");
            }
        }
    }
}

Here is the info I've logged about the error:

The remote server returned an error: (400) Bad Request.

Response Status: ProtocolError
Response Header: Cache-Control = no-cache, no-store, max-age=0, must-revalidate
Response Header: Pragma = no-cache
Response Header: Expires = Fri, 01 Jan 1990 00:00:00 GMT
Response Header: Date = Tue, 22 May 2012 05:55:54 GMT
Response Header: Content-Type = application/json
Response Header: X-Content-Type-Options = nosniff
Response Header: X-Frame-Options = SAMEORIGIN
Response Header: X-XSS-Protection = 1; mode=block
Response Header: Server = GSE
Response Header: Transfer-Encoding = chunked

回答1:

I don't know if you are still facing this issue, but your Request body should be in the same line (changed StringBuilder.AppendLine for StringBuilder.Append), and the parameters separated by "&":

StringBuilder postDataBuider = new StringBuilder();
postDataBuider.Append("code=" + this.code.Text);
postDataBuider.Append("&client_id=" + clientId);
postDataBuider.Append("&client_secret=" + clientSecret);
postDataBuider.Append("&redirect_uri=" + redirectUri);
postDataBuider.Append("&grant_type=authorization_code");

After these changes, your code works just fine and the access token is returned.