Reputation: 2914
I am using the following code to send a get request to facebook graph api oauth server.
public string GetAccessToken(string code)
{
HttpWebRequest req = (HttpWebRequest) WebRequest.Create(@"https://graph.facebook.com/oauth/access_token?client_id=249725835046216&redirect_uri=http://localhost:2794/&client_secret=APP_SECRETa&code=" + code);
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
string response=res.GetResponseStream().ToString();
return response;
}
The above code throws the following exception:
The remote server returned an error: (400) Bad Request.
Meanwhile if I type the same url in browser, it works. Please help, where am I wrong?
(P.S In the URL, I am surely replacing APP_SECRET with the secret key)
Upvotes: 1
Views: 4713
Reputation: 5510
This is what happened to me and how to solve that:
Redirect the user to
https://www.facebook.com/dialog/oauth?client_id=YOUR_APP_ID&redirect_uri=YOUR_URL
After user click allow, it'll hit our Redirect Uri
At that point we'll get the code and we need to do a server side HTTP Get to the following Url to exchange the code with our oAuth access token:
Now at step 3, I kept on getting Http 400 response back.
So after some research, I found out that on that redirect_uri
that we submitted on step 3
doesn't do anything but validate the request. Thus, the value need to match with step 2.
In short :
redirect_uri MUST MATCH both step 2
and step 3
Upvotes: 0
Reputation: 362
The redirect URL needs to be the same as the one that you posten when getting a code.
Please check this article, helped me!
http://www.ronaldwidha.net/2011/03/24/facebook-oauth-access_token-return-http-400-error-validating-verification-code/
Upvotes: 0
Reputation: 13040
You have to encode the parameters of your URL. You could use the HttpUtility class for encoding your parameters.
Upvotes: 1
Reputation: 4213
Your querystring parameters should be UrlEncoded:
HttpWebRequest req = (HttpWebRequest) WebRequest.Create(@"https://graph.facebook.com/oauth/access_token?client_id=249725835046216&redirect_uri=" + UrlEncode("http://localhost:2794/") + "&client_secret=" + UrlEncode(APP_SECRET) + "&code=" + UrlEncode(code));
Upvotes: 2
Reputation: 35225
Most probably you need to specify user agent to satisfy some check logic of a server:
HttpWebRequest req = (HttpWebRequest) WebRequest.Create(@"https://...&code=" + code);
req.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
try this and see if it helps.
Upvotes: 0