4

On the last stage of authentication against StackOverflow, I keep getting "400 Bad Request" code. It's supposed to be a simple POST request to https://stackexchange.com/oauth/access_token with a few parameters. What am i missing? Is it possible to get more info from the server about the problem ?

Any help will be much appreciated!

This is the code I use to send the request:

string code = HttpContext.Current.Request["code"];

// this is what we are sending
string post_data = "client_id={0}&client_secret={1}&code={2}&redirect_uri={3}";
post_data = string.Format(post_data, code, clientId, redirect_url, apiSecret);
post_data = HttpUtility.UrlEncode(post_data);

// this is where we will send it
string uri = "https://stackexchange.com/oauth/access_token";

// create a request
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create(uri);
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "POST";

// turn our request string into a byte stream
byte[] postBytes = Encoding.ASCII.GetBytes(post_data);

// this is important - make sure you specify type this way
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postBytes.Length;
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
Stream requestStream = request.GetRequestStream();

// now send it
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
2
  • Remove the urlencode and try. Maybe you are encoding it twice.
    – DarkXphenomenon
    Commented Jul 22, 2012 at 6:50
  • How do you get the JSON containing OAuth access token fron the response using this method? Commented Oct 25, 2012 at 9:53

2 Answers 2

2
string post_data = "client_id={0}&client_secret={1}&code={2}&redirect_uri={3}";
post_data = string.Format(post_data, code, clientId, redirect_url, apiSecret);

Shouldn't that be

string post_data = "client_id={0}&client_secret={1}&code={2}&redirect_uri={3}";
post_data = string.Format(post_data, clientId, apiSecret, code, redirect_url);
0

Try removing the urlencode, you might be encoding it twice.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .