ericoneal
ericoneal

Reputation: 148

Google OAuth2 token (Bad Request)

I can get the access key just fine, but I'm getting a (400) Bad Request error when attempting to get the token with the following code. I have tried everything. I know the credentials are correct because they work with the Google API Client. That being said, I can't use that because I need this to run in the 3.5 framework. Is there anything glaringly wrong here?

private const string clientId = "1003120056405-ofafvc699hjujp0a9952g8vjaludk90j.apps.googleusercontent.com";
private const string clientSecret = "******************";
private string redirectURI = "urn:ietf:wg:oauth:2.0:oob:auto";


public static AuthResponse Exchange(string authCode, string clientid, string secret, string redirectURI){


try
        {


            var request = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");

            string postData = string.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code&scope={4}", HttpUtility.UrlEncode(authCode), clientid, secret, redirectURI, "");

            var data = Encoding.ASCII.GetBytes(postData);

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
            request.ContentLength = data.Length;


            using (var stream = request.GetRequestStream())
            {

                stream.Write(data, 0, data.Length);
            }

            var response = (HttpWebResponse)request.GetResponse();


            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
            MessageBox.Show(responseString);
            return null;


        }

        catch (WebException ex)
        {
            MessageBox.Show(ex.Message);
            return null;
        }
    }

Upvotes: 2

Views: 1173

Answers (1)

ericoneal
ericoneal

Reputation: 148

I got this working. The code above was fine, but my accessKey was being converted to lower case by mistake. The key is case sensitive to check out the token.

Upvotes: 1

Related Questions