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.

134 Responses to “Using ASP.Net with Facebook’s Graph API and OAuth 2.0 Authentication”

  1. theA Says:

    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 ?


  2. […] Using ASP.Net with Facebook’s Graph API and OAuth 2.0 Authentication […]

  3. Wouter Says:

    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

  4. Rob Says:

    Nice piece of code saved me some time!

  5. Frank Says:

    worked beautifully! very much appreciated…

  6. Lior Says:

    webRequest.UserAgent = “[You user agent]”

    What do i need to fill here, is it just custome header?

  7. Rizaan Lakay Says:

    Why when a user logs in does it always complain about the certificate from http://www.facebook.com?

  8. Lars Christiansen Says:

    Thanks a lot works fine.
    When you have time please include example up updating status using oAuth

  9. Mohammad Ali Says:

    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?

  10. Lee Timmins Says:

    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.

  11. Lee Timmins Says:

    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.

  12. Johan Says:

    Hi

    How do i request permission to use the users e-mail?

    The FB example is:

    Cheers
    Johan

    • Johan Says:

      Oops.
      Couldnt post HTML.
      The parameter in the login in button is:
      perms=”email,user_birthday”

      • Johan Says:

        Solved it:
        string s = string.Format(“{0}?client_id={1}&redirect_uri={2}”, AUTHORIZE, this.ConsumerKey, CALLBACK_URL);
        s += “&scope=email”;
        return s;

  13. Johan Says:

    The login dosent open in a po-pup.
    Can that be solved?

  14. SKBG Says:

    Getting “Operation has times out” error when the callback comes to fbcallback.aspx page

  15. Anders Says:

    Hey,

    this made my day a bit easier, thanks a lot =)

  16. Vijai Says:

    Helped me a lot. The login popups only the first time and subsequent requests connects directly.

    • Gna Andrew Cross Says:

      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.

  17. Rashmi Pandey Says:

    Thanks a lot…
    this piece of code made think lot easier for me…
    very much appreciated… 🙂

  18. Mike B Says:

    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.

  19. mailtoanzer Says:

    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…

  20. mailtoanzer Says:

    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 😉

    • Jairo Says:

      Hey mailtoanzer,

      I am trying with the Response.Write for a FBML app and I am getting the HTTP 500 error, any idea?

      Thanks

    • Giuliano Says:

      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

  21. Ashish Says:

    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. 🙂

  22. Nick Says:

    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.

  23. Ron Jones Says:

    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?

  24. vijai Says:

    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

  25. Rakesh Says:

    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.

  26. Tal Says:

    Finally an example that works good!

  27. Adeel Says:

    hi,

    How do i get the ConsumerKey and ConsumerSecret ???

  28. Raj Says:

    Thanks, works good.

  29. Larry Says:

    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&amp;
    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

  30. Peter Says:

    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.

    • barak Says:

      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

  31. Fenil Desai Says:

    I m using the same code but getting this error:

    This webpage has a redirect loop.

    any solution…

  32. Hazel Says:

    Thanks for this works brilliantly, been looking for this for ages………..

  33. Avinash Says:

    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


  34. 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).

  35. Vishant Says:

    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?

  36. vishal Says:

    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.

  37. rich Says:

    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!

  38. dfran Says:

    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?

  39. Gna Andrew Cross Says:

    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.

  40. Nick Says:

    Are there any examples of posting an attachment to the stream (i.e image, links, etc)?

  41. Kirk Says:

    I can’t get my message to show on the wall with me/feed, rest post fine. Any thoughts?

  42. suresh Says:

    thanks for article it help me lot,

    please provide code for killing face book session using graph api(That meens logout the site)

    Thanks

  43. zes Says:

    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

  44. John secz Says:

    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?

  45. Alex Says:

    Great post, thx man!


  46. […] permissions from the user to allow your app to do stuff like post to the user’s wall, I found this C# class […]

  47. Saurab Says:

    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.

  48. Nimisha Says:

    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.

  49. Shihfan Says:

    Thanks for sharing!! It works great!

  50. Ninad Says:

    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

  51. guotao Says:

    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

  52. Deepak Says:

    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

  53. Timmy Says:

    Thanks man. Really useful!

  54. arthur Says:

    AWESOME..you are a true Life safer.
    You have no idea what this code has impact to someone life.


  55. 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 🙂

  56. Fábio Says:

    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!

  57. Phani Says:

    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…

  58. sangeeta saharan Says:

    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);

    }
    }

  59. sangeeta saharan Says:

    one more thing i m working locally..


  60. 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


  61. helped a lot thanks!

  62. john Says:

    genius post. worked first time

  63. Royston Says:

    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

  64. sangeeta Says:

    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????

  65. sangeeta Says:

    it gives exception : error 400 bad request…
    i m wrkng locally..

  66. Smitha Says:

    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


  67. 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..

  68. Smitha Says:

    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


  69. 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


  70. 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…

  71. Ashwani Says:

    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

  72. Eric Fickes Says:

    Code still works like a champ! Thanks for posting this.

  73. Alvaro Says:

    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!!

  74. Jayesh Says:

    How do you get the username or id to store in any variable in c#?

  75. Foong Says:

    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.

  76. Foong Says:

    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.

  77. Foong Says:

    Thank you very much. It took only 30 minutes and worked in first shot. It worked wonderfully.

  78. Raj Says:

    Also, has anyone tried this (or modified) code for accessing say google contacts via Oauth? Any samples/help would be great!

  79. Raj Says:

    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?

  80. Nate Shiff Says:

    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


  81. […] NOTE 2: Check the following code about Oauth 2.0 […]

  82. shahid Says:

    Great post
    Thank you my dear friend.

  83. Jobs Says:

    Thanks for this wonderfull post, it helped me a lot.

  84. sa Says:

    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.

  85. Greg Bala Says:

    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

  86. Padharia Dipti Says:

    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.

  87. Kevin Says:

    Hi may you pls send me the vb-code version and thanx in advance. My email is kevin.Makelane@gmail.com

  88. pritin Says:

    I found this article and code very helpful in getting me started. Thank you very much!

  89. TruyenNV Says:

    I got “(OAuthException) Error validating application.” What’s wrong?

  90. monika Says:

    can nyone tell me the dll use for FacebookAPI??? or how i cn import it?? hoping 4 rply

  91. jitendra1234 Says:

    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..!!

  92. Sam Says:

    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?

  93. Yushell Says:

    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?


  94. […] Using ASP.Net with Facebook’s Graph API and OAuth 2.o Authentication […]


  95. […] Using ASP.Net with Facebook’s Graph API and OAuth 2.o Authentication […]


  96. Thank you for this information! It helps me a lot)

  97. Siva L Says:

    Is anyone still facing the issue of Badrequests?


  98. 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

  99. Simon Says:

    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

  100. yuvraj Says:

    Great piece of code … Works absolutely fine… thanks for this

  101. sumit Says:

    String url=””;
    what should be value ? or should i keep it blank?
    Please tell me…after FBCallback.aspx nothing is haappen?

  102. Nic Says:

    Thanks for the code, works for me.

  103. Ayan Says:

    Hi ,It is producing 404 bad request .Can you help me plz

  104. Ayan Says:

    Is that url correct for posting msg on wall –

    url = “https://graph.facebook.com/me/likes?access_token

  105. Mr. Fixit Says:

    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

  106. Ed Says:

    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


  107. […] 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 […]

  108. Robert Brown Says:

    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

  109. joe Says:

    i love you!!! thanx for the article!…seriously! i almost gave up and changed to javascript

  110. Diego Says:

    HI, the page callback.asp never close and return to the first page.. do you know what is wrong? thanks

  111. Diego Says:

    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

  112. Nisam Says:

    (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.

  113. Nirav Says:

    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.

  114. Zeynep Says:

    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.


  115. Actually when someone doesn’t know afterward its up to other users that they will help, so here it takes place.


Leave a reply to Gna Andrew Cross Cancel reply