Nirav Bhatia
Nirav Bhatia

Reputation: 1033

google api oauth access token retrieval - 400 bad request

I'm trying to retrieve the oauth access token to make calls to some google apis in asp.net mvc, and I wrote the following code for an action:

        public ActionResult GetOAuthToken()
        {

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

        // Create a request using a URL that can receive a post. 
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        // Set the Method property of the request to POST.
        request.Method = "POST";
        request.Host = "accounts.google.com";
        // Create POST data and convert it to a byte array.
        string postData = String.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code", Request.QueryString["code"].ToString(), OAuthConfig.client_id, OAuthConfig.client_secret, OAuthConfig.token_redirect_uri);
        ASCIIEncoding encoding = new ASCIIEncoding();
        byte[] byteArray = encoding.GetBytes(postData);
        // Set the ContentType property of the WebRequest.
        request.ContentType = "application/x-www-form-urlencoded";
        // Set the ContentLength property of the WebRequest.
        request.ContentLength = byteArray.Length;
        // Get the request stream.
        Stream dataStream = request.GetRequestStream();

        // Write the data to the request stream.
        dataStream.Write(byteArray, 0, byteArray.Length);
        // Close the Stream object.
        dataStream.Close();
        // Get the response.
        WebResponse response = request.GetResponse();

        // SOME CODE TO PROCESS THE RESPONSE

        Response.Redirect("/Home");
        return View();
        }

OAuthConfig is just a class that contains the client id, client secret etc.

I keep getting 'The remote server returned an error: (400) Bad Request.' at the request.GetResponse() line. Where am I going wrong?

Upvotes: 5

Views: 3588

Answers (1)

David Waters
David Waters

Reputation: 12028

Google does provide a higher level library to work with its services, this handles the formatting of the urls and I find it makes it a lot easier to work with their apis. See http://code.google.com/p/google-api-dotnet-client/

Upvotes: 1

Related Questions