Using ASP.Net with Facebook’s Graph API and OAuth 2.0 Authentication
April 23, 2010
In case you haven’t already heard, Facebook just released their new Graph API at f8. Its good news for us developers, as the new API is much cleaner and simpler to use than their old REST API. The great news is that Facebook now supports OAuth 2.0 for authentication instead of their own custom authentication mechanism. The really great news is that OAuth 2.0 is super simple to use. If you’ve used OAuth 1.0a before, you know it can be a little tricky, with the request tokens and generating signatures and such. Well OAuth 2.0 simplifies all that, and makes using the Graph API super simple. You can read Facebook’s documentation here: http://developers.facebook.com/docs/authentication/ .
There’s example code there, but its in PHP and Python, which of course is not very useful for .Net developers. So here’s all the code you need to get running in C#.
Create a class, called oAuthFacebook.cs. A lot of this code came from a Twitter OAuth example, which I’ve modified for Facebook and OAuth 2.0:
public class oAuthFacebook { public enum Method { GET, POST }; public const string AUTHORIZE = "https://graph.facebook.com/oauth/authorize"; public const string ACCESS_TOKEN = "https://graph.facebook.com/oauth/access_token"; public const string CALLBACK_URL = "http://www.blahblah.com/facebookcallback.aspx"; private string _consumerKey = ""; private string _consumerSecret = ""; private string _token = ""; #region Properties public string ConsumerKey { get { if (_consumerKey.Length == 0) { _consumerKey = "1111111111111"; //Your application ID } return _consumerKey; } set { _consumerKey = value; } } public string ConsumerSecret { get { if (_consumerSecret.Length == 0) { _consumerSecret = "11111111111111111111111111111111"; //Your application secret } return _consumerSecret; } set { _consumerSecret = value; } } public string Token { get { return _token; } set { _token = value; } } #endregion /// <summary> /// Get the link to Facebook's authorization page for this application. /// </summary> /// <returns>The url with a valid request token, or a null string.</returns> public string AuthorizationLinkGet() { return string.Format("{0}?client_id={1}&redirect_uri={2}", AUTHORIZE, this.ConsumerKey, CALLBACK_URL); } /// <summary> /// Exchange the Facebook "code" for an access token. /// </summary> /// <param name="authToken">The oauth_token or "code" is supplied by Facebook's authorization page following the callback.</param> public void AccessTokenGet(string authToken) { this.Token = authToken; string accessTokenUrl = string.Format("{0}?client_id={1}&redirect_uri={2}&client_secret={3}&code={4}", ACCESS_TOKEN, this.ConsumerKey, CALLBACK_URL, this.ConsumerSecret, authToken); string response = WebRequest(Method.GET, accessTokenUrl, String.Empty); if (response.Length > 0) { //Store the returned access_token NameValueCollection qs = HttpUtility.ParseQueryString(response); if (qs["access_token"] != null) { this.Token = qs["access_token"]; } } } /// <summary> /// Web Request Wrapper /// </summary> /// <param name="method">Http Method</param> /// <param name="url">Full url to the web resource</param> /// <param name="postData">Data to post in querystring format</param> /// <returns>The web server response.</returns> public string WebRequest(Method method, string url, string postData) { HttpWebRequest webRequest = null; StreamWriter requestWriter = null; string responseData = ""; webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest; webRequest.Method = method.ToString(); webRequest.ServicePoint.Expect100Continue = false; webRequest.UserAgent = "[You user agent]"; webRequest.Timeout = 20000; if (method == Method.POST) { webRequest.ContentType = "application/x-www-form-urlencoded"; //POST the data. requestWriter = new StreamWriter(webRequest.GetRequestStream()); try { requestWriter.Write(postData); } catch { throw; } finally { requestWriter.Close(); requestWriter = null; } } responseData = WebResponseGet(webRequest); webRequest = null; return responseData; } /// <summary> /// Process the web response. /// </summary> /// <param name="webRequest">The request object.</param> /// <returns>The response data.</returns> public string WebResponseGet(HttpWebRequest webRequest) { StreamReader responseReader = null; string responseData = ""; try { responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream()); responseData = responseReader.ReadToEnd(); } catch { throw; } finally { webRequest.GetResponse().GetResponseStream().Close(); responseReader.Close(); responseReader = null; } return responseData; } }
Add a login button to your .aspx page:
protected void btnLogin_Click(object sender, EventArgs e) { oAuthFacebook oFB = new oAuthFacebook(); Response.Redirect(oFB.AuthorizationLinkGet()); }
Create a callback page, call it FBCallback.aspx or whatever:
protected void Page_Load(object sender, EventArgs e) { string url = ""; oAuthFacebook oAuth = new oAuthFacebook(); if (Request["code"] == null) { //Redirect the user back to Facebook for authorization. Response.Redirect(oAuth.AuthorizationLinkGet()); } else { //Get the access token and secret. oAuth.AccessTokenGet(Request["code"]); if (oAuth.Token.Length > 0) { //We now have the credentials, so we can start making API calls url = "https://graph.facebook.com/me/likes?access_token=" + oAuth.Token; string json = oAuth.WebRequest(oAuthFacebook.Method.GET, url, String.Empty); } } }
That’s all there is to it! You can start making Graph API calls by including the access token with your requests.
April 24, 2010 at 9:16 am
great post,
i am building facebook iframe application
and i did as you wrote.
but facebook return me error
{
“error”: {
“type”: “QueryParseException”,
“message”: “An active access token must be used to query information about the current user.”
}
}
i try to replace the “me” with the my user id
and it works
so how can i get the userid ?
April 26, 2010 at 11:18 am
[…] Using ASP.Net with Facebook’s Graph API and OAuth 2.0 Authentication […]
April 27, 2010 at 11:17 pm
Hi,
The oAuth service of facebook keeps giving me a internal server error (500). Should this url return a valid page https://graph.facebook.com/oauth/authorize ? even the root url gives me a 500 error.
Could you please confirm?
Thanks,
Wouter
April 28, 2010 at 9:04 am
Nice piece of code saved me some time!
April 29, 2010 at 11:29 pm
worked beautifully! very much appreciated…
May 1, 2010 at 11:08 pm
webRequest.UserAgent = “[You user agent]”
What do i need to fill here, is it just custome header?
May 1, 2010 at 11:37 pm
For user agent, you should put your application name and version. It usually looks like: “mywebsite.com/2.0”.
May 2, 2010 at 2:24 am
ok, tnx…
i am using web services alot, first time using json and http rest communication. 🙂
May 2, 2010 at 2:11 pm
Why when a user logs in does it always complain about the certificate from http://www.facebook.com?
May 4, 2010 at 5:17 pm
Thanks a lot works fine.
When you have time please include example up updating status using oAuth
May 6, 2010 at 5:51 am
What a long code. Are you sure all of them was required?
Why not read ConsumerKey and Secret from Web.config like Microsoft SDK for facebook and using WebClient instead of WebRequest?
May 10, 2010 at 3:54 am
Hi, i’d also appreciate it if you could show an example of posting to someone’s wall. I tried:
url = “https://graph.facebook.com/me/feed?access_token=” + oAuth.Token;
json = oAuth.WebRequest(oAuthFacebook.Method.POST, url, HttpUtility.UrlEncode(“Testing API”));
and also modified the oAuthFacebook.cs file and added “&scope=stream_publish” to the end of the url in the AuthorizationLinkGet method but it didn’t work.
May 10, 2010 at 6:12 am
If anyone’s interested i managed to get it to work so you can post to your feed. Change the AuthorizationLinkGet method to:
public string AuthorizationLinkGet()
{
return string.Format(“{0}?client_id={1}&redirect_uri={2}&scope=offline_access,publish_stream”, AUTHORIZE, this.ConsumerKey, CALLBACK_URL);
}
and now you can issue the following request:
var url = “https://graph.facebook.com/me/feed?access_token=” + oAuth.Token;
var json = oAuth.WebRequest(oAuthFacebook.Method.POST, url, “message=” + HttpUtility.UrlEncode(“TestingAPI”));
Hope this helps.
July 16, 2010 at 10:50 am
@Lee – you are awesome – I have been strugglin with this for 2 days – ur solution worked like a charm!
October 6, 2010 at 7:14 am
Lee, thanks for getting back! I’ve searched all over the net and found it here. Good job.
April 22, 2011 at 4:16 am
You are amazing!
I was googling for 2 days with all sorts of errors. This piece of code made my day!
Thanks a lot…
May 11, 2010 at 6:20 am
Hi
How do i request permission to use the users e-mail?
The FB example is:
Cheers
Johan
May 11, 2010 at 6:21 am
Oops.
Couldnt post HTML.
The parameter in the login in button is:
perms=”email,user_birthday”
May 11, 2010 at 6:56 am
Solved it:
string s = string.Format(“{0}?client_id={1}&redirect_uri={2}”, AUTHORIZE, this.ConsumerKey, CALLBACK_URL);
s += “&scope=email”;
return s;
May 11, 2010 at 6:57 am
The login dosent open in a po-pup.
Can that be solved?
May 21, 2010 at 7:19 am
Getting “Operation has times out” error when the callback comes to fbcallback.aspx page
June 2, 2010 at 1:56 am
Hey,
this made my day a bit easier, thanks a lot =)
June 10, 2010 at 12:38 pm
Helped me a lot. The login popups only the first time and subsequent requests connects directly.
October 26, 2010 at 4:38 am
Will you just provide me the details to avoid the login popups routinely or would you tell us what are the details you stored for future purpose.
June 16, 2010 at 5:53 am
Thanks a lot…
this piece of code made think lot easier for me…
very much appreciated… 🙂
June 21, 2010 at 8:09 am
Thank you for posting this. I had something similar that “worked”, but not nearly as refined. Definitely a help in getting an app I was working on working well.
June 27, 2010 at 9:45 pm
How can I use it for a Facebook FBML canvas application? My requirement is to get the list of friends of a logged in user…
July 5, 2010 at 5:38 am
I figured how to use the autrhentication with FBML canvas app.. if anyone want to know
use following
Response.Write(string.Format(“”, oFB.AuthorizationLinkGet()));
instead of
Response.Redirect(oFB.AuthorizationLinkGet());
Thanks again for the excellent sample.. my first graph API fb app will be up tomorrow 😉
August 30, 2010 at 3:18 pm
Hey mailtoanzer,
I am trying with the Response.Write for a FBML app and I am getting the HTTP 500 error, any idea?
Thanks
September 1, 2010 at 10:00 am
Hi mailtoanzer, can you send me the code how do you get to make this work with canvas? I can’t get to work with a canvas application the canvas show a facebook logo that the user have to click to go to connect page.
Thxs my mail is giuice@gmail.com
July 13, 2010 at 4:15 am
Hi trancealot,
It’s a really great example and good thing is, this is working for first run. thanks a lot to you.
thanks, thanks, thanks, thanks, thanks, thanks, thanks, and lots of thanks to you. 🙂
July 25, 2010 at 7:20 pm
Are there any examples of getting to the properties? Say for instance I just need to return the ID, First Name, or Home town city. How would I go about doing that? I feel like I’m just overlooking something.
Thanks for any help.
August 1, 2010 at 7:49 am
Thanks for the really nice example here.
Have one question about something I’m struggling with. After the oAuthFacebook object has been created and access granted by the user through the Facebook redirect, is there a way to list all the extended permissions that have been granted?
August 3, 2010 at 12:40 pm
This might help some one. If you want to post to someone else wall do this
var url = “https://graph.facebook.com/friendfacebookId/feed?access_token=” + oAuth.Token;
var json = oAuth.WebRequest(oAuthFacebook.Method.POST, url, “message=” + HttpUtility.UrlEncode(“to my friend”));
where friendfacebookid should be replaced with the actual friend facebook Id
August 14, 2010 at 2:31 am
Hi i am using same code in my local application to access facebook api,but here i am getting a exception for this line
webRequest.UserAgent =http://localhost:2181/3.5;
The type initializer for ‘System.Net.WebHeaderCollection’ threw an exception.
August 15, 2010 at 7:13 am
Finally an example that works good!
August 17, 2010 at 11:41 pm
hi,
How do i get the ConsumerKey and ConsumerSecret ???
August 19, 2010 at 10:05 am
Thanks, works good.
August 26, 2010 at 3:25 am
Hi,
Really thanks for this clear example, but i have an issue.
When I fo the webRequest for https://graph.facebook.com/oauth/access_token?client_id=XXXXXXXXXXXX&
redirect_uri=http://www.MyWeb.com/catcher.aspx&
client_secret=YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY&
code=ttttttttttt-aaaaaaaaaaaaaaa-bbbbbbbbbbbbbbbbb”
The server return a 400 bad request error.
Any ideas?
Thanks
August 26, 2010 at 4:41 am
Hi,
Great bit of code – I’ve just been playing around with it in order to post some messages to my Facebook wall – I had success only once i realised i needed to ensure i had been granted extended permissions to do this. To make this happen on 1st request I appended the scope parameter to the following function
public string AuthorizationLinkGet()
{
return string.Format(“{0}?client_id={1}&redirect_uri={2}&scope=publish_stream”, AUTHORIZE, this.ConsumerKey, CALLBACK_URL);
}
When i 1st login to FB and the app requests permissions from me it has the additional copy about granting rights to publish to the wall. without this permission being set here i found the server would always return a 500 error. Hope that helps others using this code.
October 21, 2011 at 2:51 pm
i was looking for this “SCOPE” magic word i used parms ext+pemissions etc and it didnt work how the hell did you fing this word? i didnt find it on FB…
thanks any way
September 3, 2010 at 2:47 am
I m using the same code but getting this error:
This webpage has a redirect loop.
any solution…
April 6, 2011 at 1:27 am
It seems that u put the button in the FBCallback.aspx page. check this
October 19, 2011 at 11:21 pm
Hi,
I am also getting the same error of redirection loops.
Any solution?
September 7, 2010 at 8:54 am
Thanks for this works brilliantly, been looking for this for ages………..
September 20, 2010 at 1:11 am
Hi,
Whenever there is a call to get the “access_token”, I get the error “Bad Request (400)”. Any idea what I am missing.
I have given valid application Id and Secret. What should I be filling for the User Agent?
Regards,
Avinash G
September 29, 2010 at 1:12 am
Great post!! I taken a slight different approach and have built a small website, where the code rebuilds the json string from Facebook into .NET objects. You can view my post and download the start of a basic api here:
http://you.arenot.me/2010/09/28/facebooks-graph-api-and-asp-net/
(code is at the bottom of the article).
October 5, 2010 at 7:28 am
This is fabulous post and the user comments too. 🙂
Helped me a lot in integration.
Just one question.
How to logout once the user logs in to website using FB?
October 15, 2010 at 4:05 am
This is really very good.I think facebook should include this url or include this code in there examples. I was searching this from last 2 weeks.
October 21, 2010 at 11:07 pm
So after they login, and you get the
oAuth.AccessTokenGet(Request[“code”]);
How do you get this when needed to make subsequent calls? there is some FB cookie right?
Sorry if this is a dense question.. I’m assuming we have access to a cookie that is created by FB once the user logs in? Thanks!
October 25, 2010 at 11:26 am
When sending the request for the authorization token, I get the error “The server return a 400 bad request error.” Can someone please clarify as to what is wrong with the request being sent?
October 26, 2010 at 3:16 am
Thanks for your code.
It does not return to the call back url if the call back url is set to localhost for testing purpose. NOTE: The localhost is formed correctly.
Need samples to access other details also available with the facebook for the allowed users.
November 4, 2010 at 5:36 pm
Are there any examples of posting an attachment to the stream (i.e image, links, etc)?
November 10, 2010 at 5:09 pm
I can’t get my message to show on the wall with me/feed, rest post fine. Any thoughts?
November 13, 2010 at 11:04 am
thanks for article it help me lot,
please provide code for killing face book session using graph api(That meens logout the site)
Thanks
November 18, 2010 at 2:22 am
I’ve tried the code but keep getting this error
The operation has timed out
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Net.WebException: The operation has timed out
can anyone help me with this?
i’m using iframe canvas type
and run it from localhost
November 19, 2010 at 12:03 am
can i use this code to make a post to certain xid comments, if it could be done……
can any body help me with the code?
November 20, 2010 at 10:27 pm
Great post, thx man!
December 3, 2010 at 9:27 pm
[…] permissions from the user to allow your app to do stuff like post to the user’s wall, I found this C# class […]
December 13, 2010 at 2:34 am
I tried teh code, but getting an error that the redirect_uri is not formed, the “&” is turning to “&” if I correct it manually and use teh URL it works just great. Need help.
December 23, 2010 at 12:52 pm
I am yet another victim of the Bad Request issue – have been hunting for days now.
Any ideas, what could be wrong with this request?
I have used the above code, and I suspect the issue is with my redirect uri:
http://nimi-6.devdom.extest.xxxx.com/callback.aspx
Any ideas?
Looks like a lot of people are seeing this issue.
December 28, 2010 at 1:39 am
Thanks for sharing!! It works great!
January 4, 2011 at 6:08 am
Hi,
Thanks for the code. It seems to be working for all but not for me.
When I am calling GetAccessToken function I am getting The remote name could not be resolved: ‘graph.facebook.com’ error.
But while trying to debug, If I take the access_token URL and Hit it in browser I do get the Auth token. Am I Missing anything here?
Thanks,
Ninad
January 21, 2011 at 8:14 pm
https://graph.facebook.com/oauth/authorize&scope=publish_stream,friends_notes?client_id=158496750832347&redirect_uri=http://www.vamosinc.com/vamostest/default.aspx?F=F
After the operation error :
{
“error”: {
“type”: “OAuthException”,
“message”: “Invalid redirect_uri: \u5e94\u7528\u7a0b\u5e8f\u914d\u7f6e\u4e2d\u662f\u4e0d\u5bb9\u8bb8\u63d0\u4f9b\u7f51\u7ad9\u5730\u5740\uff08URL\uff09\u7684\u3002”
}
}
why? thx
January 25, 2011 at 3:01 am
This is a brilliant post… Much cleaner than I came across posts in 3 days of struggle. How do we set permission variables? Like to retrieve friends list one needs to set friendlist_membership permission
January 26, 2011 at 8:31 am
Thanks man. Really useful!
February 3, 2011 at 6:24 pm
AWESOME..you are a true Life safer.
You have no idea what this code has impact to someone life.
February 11, 2011 at 9:52 am
Thank you for this great post men!!!
I have been looking day after day for a way to allow permission without the annoying popups and FB.ui / FB.login didnt help!
After the permission I was getting the code, but did not know how to get the access token from there. your method AccessTokenGet() was point!!
Thank you for saving developer time
really appreciate your post 🙂
February 16, 2011 at 9:55 am
Thank you! It works great!
But I have a question.
How do I get the user information, like e-mail, userId, name, etc?
Thanks again, you made my day!
February 16, 2011 at 11:12 pm
Hi,
This is an excellent post. I have moved from FBML to IFrame Garph API.
FB recently introduced IFrame applications in the Page. Now my requirement how do I get the pageid where the application is added.
Can any please help me. I have been having troubles getting the pageid. As per the documentation of fb it would reside in the signed_request. I dont see anything like that here.
Thanks in advance.
Phani…
February 23, 2011 at 1:20 am
hi..
i am getting an error while accessing token..
“redirect uri is not valid”
when page loads its finds that request [“code”] is null, then it redirects to
Response.Redirect(oAuth.AuthorizationLinkGet());
and gives error
{
“error”: {
“type”: “OAuthException”,
“message”: “Invalid redirect_uri: Given URL is not allowed by the Application configuration.”
}
}
here is my code..
if (Request[“code”] == null)
{
//Redirect the user back to Facebook for authorization.
Response.Redirect(oAuth.AuthorizationLinkGet());
}
else
{
//Get the access token and secret.
oAuth.AccessTokenGet(Request[“code”]);
if (oAuth.Token.Length > 0)
{
//We now have the credentials, so we can start making API calls
url = “https://graph.facebook.com/me/id?access_token=” + oAuth.Token;
string json = oAuth.WebRequest(oAuthFacebook.Method.GET, url, String.Empty);
}
}
February 23, 2011 at 1:25 am
one more thing i m working locally..
March 6, 2011 at 10:02 am
nice!
for those who are trying to make it work, first check if you have applied the necessary settings in your facebook app page. I think most errors root from there.
also, reading few APIs won’t hurt. developers.facebook.com
March 8, 2011 at 5:51 am
helped a lot thanks!
March 9, 2011 at 8:46 am
genius post. worked first time
March 15, 2011 at 5:57 pm
hello guys….this is a wonderful piece of code and i’m extremely glad i found it. however, like some other people who have posted above i have also encountered the “400 Bad Request error”. I believe this has to do with the WebRequest method which accepts a url. My url is in the form:
string accessTokenUrl = string.Format(“{0}?client_id={1}&redirect_uri={2}&client_secret={3}&code={4}”, ACCESS_TOKEN, this.ConsumerKey, “http://vencube.com”, this.ConsumerSecret, authToken);
i have ascertained that my consumerKey and consumerSecret are correct, but it still throws an exception. Anybody with a solution should kindly help. Thank you
April 15, 2011 at 1:05 am
if (Request[“code”] == null)
{
//Redirect the user back to Facebook for authorization.
Response.Redirect(oAuth.AuthorizationLinkGet());
}
else
{
//Get the access token and secret.
oAuth.AccessTokenGet(Request[“code”]);
if (oAuth.Token.Length > 0)
{
//We now have the credentials, so we can start making API calls
url = “https://graph.facebook.com/me/id?access_token=” + oAuth.Token;
string json = oAuth.WebRequest(oAuthFacebook.Method.GET, url, String.Empty);
}
}
i have used the above code in my canvas page on page load..
wen page loads it first goes to if block always, shows an exception then loads again and goes in else block..
y this all is hpng????
April 15, 2011 at 1:06 am
it gives exception : error 400 bad request…
i m wrkng locally..
April 18, 2011 at 12:20 pm
Hi,
When is the request null and when does it have a value.
I am getting an error Bad Request Http 400
if (method == Method.POST)
{
webRequest.ContentType = “application/x-www-form-urlencoded”;
//POST the data.
requestWriter = new StreamWriter(webRequest.GetRequestStream());
Any clues?
Thank u
April 23, 2011 at 8:57 am
Great work. Now to parse all of that data 😀
I also got a Bad Request Error Http 400 It was when I was trying to post back to the same page that I called from, managing the flow in the code.
The authentication requires that the visitor be forwarded, to the accept app to access your FBdata, if they haven’t authenticated and then redirected by facebook to the app page.. Well that was my issue, hope it helps..
April 24, 2011 at 11:23 pm
Hi, Thanks for the code.. Really helps a beginner like .Net My Graph APi code is not working as expected..
Once the user logs in and enters his user name and pwd correctly, the OAUth dialog box should pop up asking to “Allow Permissions..” Then it has to get the Access token.. but here it is directly going to get the access token and not asking to allow permissions..
So in the final step rl = ” https://graph.facebook.com/me/inbox?access_token=” + oAuth.Token;
json = oAuth.WebRequest(oAuthFacebook.Method.GET, url, String.Empty);
MailBox mb = js.Deserialize(json);
if (mb.data.Count > 0) inbox.Visible = true;
grvMail.DataSource = mb.data;
grvMail.DataBind();
It fails because of The remote server returned an error: (403) Forbidden.
the website said needs mailbox permissions
Please shed some light..
This thing is not working since 2 weeks
Thanks
Smitha
April 26, 2011 at 6:40 am
Hi,
I am using the same set of code in my application and it works fine, but sometime i am getting the 400, bad request error. I don’t which one i am missing from here. Please let me know If anyone knows about this issue..
Thanks
Sankar
April 29, 2011 at 1:44 pm
This works brilliantly…EXCEPT, I am either stuck in an endless loop trying to get the app into the facebook frame or end up with my app not in facebook when trying to get the auth page in the top frame..
Is driving me mad, can anyone shed some light on this as no-one else seems to be asking this question…
May 17, 2011 at 12:56 am
Thanks A lot
Nice piece of code
can u help us for “Log out” functionality server side
i have implemented serverside code forl FB implementation and tried javascript sdk
for logout just added ref of all.js file and call fb.logout() function no error but no result as wel
May 22, 2011 at 1:42 pm
Code still works like a champ! Thanks for posting this.
May 24, 2011 at 2:08 pm
this code is awesome!!! btw, for people trying to use, this worked for me only when I publised the pages to my personal web page, I think it’s because fb redirects you to an actual existing page.
thank you, thank you for the code!!
June 1, 2011 at 7:18 am
How do you get the username or id to store in any variable in c#?
July 25, 2011 at 10:20 pm
Thank you very much. The solution works wonderfully. It took me only 30 minutes and worked in first shot. No error at all. Thank you.
July 25, 2011 at 10:24 pm
Oh, oh, almost forgot about it. I converted the code into VB.Net. If anyone interested in the VB version, feel free to send me an email. I will be very happy to reply back with the code. Thanks.
August 4, 2011 at 1:42 am
Complete newbie here
Managed to get this running with vb.net and on my callback page I am getting the code. What now> How can I do a test graph call to see what is going on?
Thanks
Raj
August 15, 2011 at 8:53 pm
Please send the VB code to me. I am so interested. Thanks a lot . king4arabs@gmail.com
March 7, 2012 at 2:57 am
hi there,
I would seriously appreciate it if you could reply with the VB code?
Thanks.
June 6, 2013 at 6:18 am
Please send the VB code to me. I am so interested. Thanks a lot . manuelarroz@gmail.com
July 25, 2011 at 10:27 pm
Thank you very much. It took only 30 minutes and worked in first shot. It worked wonderfully.
August 4, 2011 at 1:43 am
Also, has anyone tried this (or modified) code for accessing say google contacts via Oauth? Any samples/help would be great!
August 4, 2011 at 7:07 am
Ive actually got it working with Google for the first few steps but i get a 400 Badrequest error when calling AccessTokenGet.
Google’s documentation says perform a post but even this doesnt seem to make any difference.
Any ideas?
August 15, 2011 at 2:37 pm
[…] Using ASP.Net with Facebook’s Graph API and OAuth 2.0 Authentication https://osnapz.wordpress.com/2010/04/23/using-asp-net-with-facebooks-graph-api-and-oauth-2-0-authenti… […]
August 16, 2011 at 10:11 pm
Dear author(s),
My entire study group is in love with you. Your code is a dream. We love you!
We’re in CS 5950 – .NET Distributed and Web Applications at Western Michigan University. Part of our final assignment was using an original ASP.NET app to have a user log in to Facebook and retrieve their friends list. This was a huge pain, particularly because we were using Visual Studio’s local ASP.NET development server. Your glorious code has allowed the creation of a successful app. Yay!
Thanks again,
Love Nate
August 16, 2011 at 10:19 pm
[…] NOTE 2: Check the following code about Oauth 2.0 […]
August 19, 2011 at 4:22 am
Great post
Thank you my dear friend.
September 5, 2011 at 12:43 pm
Thanks for this wonderfull post, it helped me a lot.
September 14, 2011 at 4:29 am
Only decent post which works as it is without any complication and has error messages to say what is going wrong. Great job mate. Thanks a ton.
September 27, 2011 at 12:05 pm
to all those with “bad request” problems, see http://stackoverflow.com/questions/3924262/400-bad-request-when-requesting-facebook-access-token
I had the same issue, turns out that i had a “?” at the end of the return_uri. removing it fixed the problem
October 7, 2011 at 12:56 am
I integrate facebbok login with my asp.net application…but now problem with the logout using facebook login from my application.
its not cleared cookies or session created at login time…
i do not use facebook logout button . its a simple asp:button. i have to code for logout on this button.
Please reply me soon.
i stuk here. please help me out.
thanks in advance.
October 7, 2011 at 1:02 am
i m using same this forum for login tnto my application.
but now issue for
October 17, 2011 at 11:47 pm
Hi may you pls send me the vb-code version and thanx in advance. My email is kevin.Makelane@gmail.com
October 30, 2011 at 10:29 am
I found this article and code very helpful in getting me started. Thank you very much!
November 10, 2011 at 5:52 pm
I got “(OAuthException) Error validating application.” What’s wrong?
November 18, 2011 at 4:39 am
can nyone tell me the dll use for FacebookAPI??? or how i cn import it?? hoping 4 rply
November 21, 2011 at 12:18 am
Hello Sir,
I want Exactlly you had done in ASP.Net so I Required for WPF I had converted into the WPF but some where it give me error like this Request and HttpUtility so is there any other way so that I can go ahead and take forward it .
thank you very much..!!
November 22, 2011 at 9:23 am
Code is working great!
Where in this code would I request the user id, email & name? How would I access it when returned by facebook?
November 25, 2011 at 5:23 pm
1) I put the oAuthFacebook class in Default.aspx.cs, and the Button on Default.aspx.
2) Created FBCallback.aspx and put Page_Load code there.
Problem: When I click on the button. I get the login in at facebook. Then, I’m redirected to FBCallback.aspx. There’s where I get the error.
I’m getting Compilation Error:
—————————————–
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS0246: The type or namespace name ‘oAuthFacebook’ could not be found (are you missing a using directive or an assembly reference?)
Source Error:
Line 17: {
Line 18: string url = “”;
Line 19: oAuthFacebook oAuth = new oAuthFacebook();
Line 20:
Line 21: if (Request[“code”] == null)
Source File: c:\Inetpub\wwwroot\dev\FBCallback.aspx.cs Line: 19
—————————————–
What am I doing wrong? I followed the instructions.
Also, can anyone provide a working example?
How do I make a call to the API for the user birthday, to save it in a variable afterwards?
December 27, 2011 at 7:41 pm
[…] Using ASP.Net with Facebook’s Graph API and OAuth 2.o Authentication […]
December 29, 2011 at 9:32 am
[…] Using ASP.Net with Facebook’s Graph API and OAuth 2.o Authentication […]
January 25, 2012 at 8:50 am
Thank you for this information! It helps me a lot)
February 4, 2012 at 1:48 pm
Is anyone still facing the issue of Badrequests?
February 25, 2012 at 3:26 pm
Very useful article, thanks. I’ve successfully implemented this in VB.NET and adapted it like the previous comments suggested. Been wanting to use Facebook with ASP.NET for a while now!
Cheers
February 27, 2012 at 4:20 am
Hi, I always get an error when i run this piece of code. Everything works fine. I get the token and everything is perfect, until i run the fbcallback load_page. Then i always get a time out in the WebResponseGet()
Can anybody help me please 🙂
Regards
Simon
March 8, 2012 at 11:31 pm
Great piece of code … Works absolutely fine… thanks for this
April 3, 2012 at 10:40 pm
String url=””;
what should be value ? or should i keep it blank?
Please tell me…after FBCallback.aspx nothing is haappen?
April 20, 2012 at 2:26 pm
Thanks for the code, works for me.
May 25, 2012 at 4:59 am
Hi ,It is producing 404 bad request .Can you help me plz
May 26, 2012 at 2:52 am
Is that url correct for posting msg on wall –
url = “https://graph.facebook.com/me/likes?access_token
June 12, 2012 at 9:49 pm
After hours of searching around I finally found a good solution to the facebook access_token request returning “Bad Request 400”.
The return_uri param sent to “https://graph.facebook.com/oauth/access_token” must be exactly the same uri as the one sent “to https://graph.facebook.com/oauth/authorize“
July 9, 2012 at 9:23 am
Code works great! Bravo.
To help others with the 404 bad requests, here’s two areas where you might be tripping on,
1 – replace the user agent with,
webRequest.UserAgent = HttpContext.Current.Request.UserAgent;
that’ll get the user agent string from the user.
2 – remember to translate the code param returned from FB into an access token and then pass back that access token back to FB when you make your API call (same as example code provided – “Create a callback page, call it FBCallback.aspx or whatever:”)
You’ll just need to modify the /me/ GraphAPI call based on what you want
July 18, 2012 at 3:36 pm
[…] I copied a C# class written by Tuyen Nguyen from Osnapz. This class is used to do the actual work of the oAuth 2.0 […]
October 7, 2012 at 5:32 pm
i would also like to say this code is fantastic.. Took me 1 hour to be able to update Twitter, but 3 days going over so much code trying to figure out how to update Facebook, then I stumbled onto this.
Also, 404 Errors are cased by you app not supply the same domain as the callback domain.
I had this working perfectly with localhost, added the code into a live site then started getting 404 errors. When into the FB app, changed all the urls from localhost to the domain the web page is in and worked perfectly after that
October 14, 2012 at 11:20 pm
i love you!!! thanx for the article!…seriously! i almost gave up and changed to javascript
June 29, 2013 at 5:59 pm
HI, the page callback.asp never close and return to the first page.. do you know what is wrong? thanks
July 1, 2013 at 7:07 am
HI, It works great for me.. but I have this issue… After I call FBCallback.aspx and do all the authentication required, the page stays open. I need to close than window and came back to login.aspx so i use de user data in that page… Is that posible? Another issue, is that the dialogBox is not a PopUp, it is Page..syle.
Thanks
July 11, 2013 at 11:16 pm
(HttpWebRequest)WebRequest.Create(string.Format(“https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}”, strClientID, “http://www.facebook.com/connect/login_success.html”));
I am using this code.
But i getting operation has timed out error.
Can you please help me to resolve this issue.
July 22, 2013 at 7:31 am
Hi, This code was working fine with our application. but, I think after facebook changes, it is not working now.
Is anyone getting the same problem?, or is anyone has fix the problem.
Thanks.
February 6, 2014 at 4:36 am
this is what i am looking . There are a lot of examples but all are too complicated. Everybody writes their own frameworks but this is the basic and needed one.
August 21, 2014 at 6:08 pm
Actually when someone doesn’t know afterward its up to other users that they will help, so here it takes place.