(400) Bad Request getting Access Token - C#


#1

I am using the following c# code to try and Get the OAuth 2.0 Access Token and Refresh Tokens.
I have been following the API guide: http://developers.hubspot.com/docs/methods/oauth2/get-access-and-refresh-tokens

I already got a code from the user authorizes my app
When I run the below code it fails at "WebResponse response = request.GetResponse();"
The error is: The remote server returned an error: (400) Bad Request

Any help would be appreciated.

Thanks

        WebRequest request = WebRequest.Create("https://api.hubapi.com/oauth/v1/token/");
        request.Method = "POST";

        var postData = "grant_type=authorization_code";
        postData += "&client_id=XXXX";
        postData += "&client_secret=BBBBB";
        postData += "&redirect_uri=http://www.hubspot.com/";
        postData += "&code=FFFF";

        byte[] byteArray = Encoding.UTF8.GetBytes(postData);

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

        Stream dataStream = request.GetRequestStream();

        dataStream.Write(byteArray, 0, byteArray.Length);

        dataStream.Close();

        WebResponse response = request.GetResponse();

        Console.WriteLine(((HttpWebResponse)response).StatusDescription);

        dataStream = response.GetResponseStream();

        StreamReader reader = new StreamReader(dataStream);

        string responseFromServer = reader.ReadToEnd();

        Console.WriteLine(responseFromServer);

        reader.Close();
        dataStream.Close();
        response.Close();

#2

Hi @Davey1971

Are you able to log the body of that error response? The postData look ok, but there should be more details for the problem in the body of that response.


#3

I was able to get error information, thanks for that suggestion.

I tried Initiating an OAuth Connection again using the following

https://app.hubspot.com/oauth/authorize?client_id=XXXX&scopes=contacts&redirect_uri=http://www.hubspot.com

I Authorized my Test Portals and took the Code that was returned in the URL and put it into my C# app.
I ran the C# application and this is the error message I received
{“error”:“invalid_grant”,“error_description”:“missing or unknown auth code”}

Not sure why I am getting this error. I checked the Client ID and the Client Secret for my App and it is correct in my C# app


#4

I am getting
The remote server returned an error: (400) Bad Request


#5

redirect_uri needs to be exactly the same as it was in the initial authorization url. Why? ¯_(ツ)_/¯


#6

Thank you Erik from 2017 that solve my issue in 2018. Get some Bitcoin.