Facebook Login with ASP.NET Web Forms


Join my mailing list!

One of the core functions of any modern app is the ability to leverage Social Authentication (also known as Social Login).  Social login is a form of single sign-on using existing login information from an identity provider such as Facebook, Twitter, Google or Microsoft to sign into a third party website or app in lieu of creating a new login account specifically for that app.  The mechanism is designed to simplify logins for end users as well as provide more reliable demographic information to developers.

Under the covers, Social login is actually powered by OAuth.  OAuth is an open standard for authorization.  OAuth provides client applications ‘secure delegated access’ to server resources on behalf of a resource owner. It specifies a process for resource owners to authorize third-party access to their server resources without sharing their credentials. Designed specifically to work with Hypertext Transfer Protocol (HTTP), OAuth essentially allows access tokens to be issued to third-party clients by an authorization server, with the approval of the resource owner, or end-user. The client then uses the access token to access the protected resources hosted by the resource server.  OAuth is commonly used as a way for web surfers to log into third party web sites using their Facebook, Twitter, Google or Microsoft accounts, without worrying about their access credentials being compromised.

Years ago, when I first began working with Social Login and OAuth, I found the concept to be somewhat complicated and difficult to implement from scratch.  I attempted using third party libraries such as the Facebook SDK for .NET however it did not assist me in truly understanding the underlying concept.  After much research on the topic I discovered the following graphic which I found to be quite helpful:

The more I worked to understand it, the more I realized that it is simply just a series of calls to various endpoints (URIs) which in sequence gets me to the expected result.

As I went about deciding which identity provider to use it was initially obvious that the one with the largest number of users would make the most sense.  If I’m building an app for the masses, then I want to make sure that I provide users with the easiest way for them to login to my app.  Therefore the obvious choice was Facebook which currently has approximately 1.3 billion active users.

According to identity management platform Gigya, for the first time since 2011, Facebook has surpassed the 60 percent mark and powered 61 percent of all social logins on Gigya’s network in the last quarter of 2014 (up from 58 percent in the previous quarter and up 10 percent from a year ago).

This made the decision to implement Social Login with Facebook a no-brainer.  Once this decision was made I set out to find any code samples online that used ASP.net and even more specifically Web Forms.  I quickly discovered that a simple, straight forward example simply did not exist.  As of Visual Studio 2013 the option to create a new ASP.net Web Application project using ‘individual user accounts’ from social identity providers became available however, again, this did not lend to the level of control I was looking for.

Without searching much further I took on the task of doing this myself and have now also created a sample project which you can download and incorporate into your app.

The sample project does the following:

  1. Authenticates the user via Facebook
  2. Makes a requests to Facebook for the user’s public profile information
  3. Display the user’s information

Before you use the following sample you must create a Facebook application. To do so navigate to https://developers.facebook.com/apps and click the ‘+ Add a New App’ button. Follow the steps to create an app and record your AppId and AppSecret.

Once you have your AppId and AppSecret all you need to do is following:

  1. Download the project from GitHub
  2. Open the project in Visual Studio
  3. Open the Web.config and add your AppId and AppSecret in the <appSettings> section
  4. Run the project.

This is the result you should get:

The following is the core logic:

And there you have it.  Please let me know in the comments if you have any issue with concept or with the sample project… would be happy to help.

In upcoming blog posts I will discuss how to:

  • Request additional information from facebook that requires user permissions such as ‘email address’ and ‘location’.
  • Submit posts back to facebook on behalf of the user

Download the full source code on GitHub:
https://github.com/nickpinheiro/FacebookLoginASPnetWebForms

Additional Resources:

Other posts in the Facebook Development series:

Don’t miss a thing…

Join my mailing list!

Comments (56)

  1. drilldriversq.com says:

    Thank you very much

  2. developerchick says:

    Thank you very much, this worked for me.  I was wondering though, how do you go about logging someone out?

  3. Nick Pinheiro says:

    @developerchick – Glad it worked for you 🙂  In terms of logging out… are you referring to logging the user out of your application or Facebook?

  4. developerchick says:

    @Nick – I have the code setup already for logging the user out of my application already so it would just be facebook.  I didn't know if you could do a Response.Redirect and then change the attributes to something that indicates the state is now logged out?  I am not sure how it works.

  5. Nick Pinheiro says:

    @developerchick – Ok, then all you would need to do is use the Facebook JavaScript SDK 'Logout' function: developers.facebook.com/…/v2.3  Let me know if you need any assistance implementing this.

  6. developerchick says:

    @Nick – yeah I am not sure how to implement that exactly after utilizing your code above.  I would think there was some sort of way to continue with what you were doing with using Response.Redirect to send attributes.  I am new to facebook integration and your solution what the ONLY one that made sense to me AND worked.  Thank you again for that.  

  7. Nick Pinheiro says:

    @developerchick – Ok, I actually think adding logout functionality to this solution would be a nice addition.  Give me a day or two and I will add it in.  I will notify you here once included.

  8. developerchick says:

    @Nick – thanks, I appreciate it. Also, I had one other question.  For every page I have in my application, do I need to link to each page using that Response.Redirect with the facebook path and credentials?

  9. Nick Pinheiro says:

    @developerchick – No, the idea is that you only link to that once when the user initially logs in.  Once they've logged in and you have their user information from Facebook, you should store their information in your application database.  You would then reference your database for their user information from subsequent pages in your application.  The second time they login (and all additional times) you can simply update your database with their latest user information from Facebook.

  10. developerchick says:

    @Nick – Okay, that is what I thought.  I was just wondering because now I see my code for my share button on my main landing page (which comes after the user is logged in) isn't working and facebook states "there's an error in the application".  It is strange though as I haven't touched this page and it worked before I implemented the login code.  I am wondering, to get my share button working (which it is a dynamic share button as there are multiple share buttons on this landing page depending upon how many user posts are on the page) I have the text and attributes being displayed using jQuery and my function to connect to facebook with my appid, etc… is in my master page.  Is it possible that having your connection code redirecting the user to the landing page AND having another facebook connection within the master page is causing a conflict?

  11. developerchick says:

    @Nick – forget it, found some old code I had forgotten to un-comment.  My fault! 🙂  Let me know about the logout.  Thanks again!

  12. Tu says:

    I got this error:

    "Given URL is not allowed by the Application configuration: One or more of the given URLs is not allowed by the App's settings. It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App's domains."

    Please help me to fix it.

  13. Nick Pinheiro says:

    @Tu – Simply go to 'developers.facebook.com', navigate to your appropriate app under 'My Apps' and on the left hand navigation click on 'Settings'.  In the center of the page click on 'Add Platform', select 'Website' from the popup dialog.  In the new 'Website' section, in the 'Site Url' field enter 'http://localhost/&#39;.  Lastly, in the section above websites enter 'localhost' in the 'App Domains' field.  Click 'Save Changes' and retry your web application again.  Let me know how you make out.  I will add this to the blog post as well as all others will need to follow the same process.

  14. Tu says:

    @Nick – I followed your instructions, but there's still that error @@

  15. Nick Pinheiro says:

    @Tu – Please email me screenshots of your app settings in the Facebook Developer Portal as well as your browser when you received the message.  Send to: nickpinheiro@outlook.com

  16. Tu says:

    @Nick – I sent an email to you. Thank you.

  17. Xchange says:

    Hello i get an error in return process The remote server returned an error: (400) Bad Request. please help 🙂 satmythuatviet.com/Untitled-ee1.jpg

  18. Nick Pinheiro says:

    @Xchange – Please ensure that your 'FacebookAppId' and 'FacebookAppSecret' are entered properly in the web.config.

  19. Anonymous says:

    Thanks bro..nice and simple

  20. Anonymous says:

    Hey Nick, thanks for the description. I am running it from IIS and get the following errors. When using the actual URL from IIS i get the error: "Given URL is not allowed by the Application configuration…"

    When using Localhost i get the error: "Could not connect to localhost".

    What am I missing? I appreciate your help 🙂

  21. @Robin – Have you first been able to get the solution to work within Visual Studio?

  22. Anonymous says:

    @Nick: The Problem seems to happen with the redirect_uri. Its probably related to me trying to run it from a local server via IIS. Is that possible at all, because Facebook cannot access it from outside?

    I tried the official Javascript SDK first, which worked. But runnig it via asp so far is a mess… 🙁

  23. Anonymous says:

    Okay, I solved it. I had to change redirect_uri in user.aspc.cs to the actual URL, then it worked.

    You mentiones an upcoming Blogpost about including Email to the fetched data. Is that difficult to add to this solution here?

  24. Anonymous says:

    Hi Nick, Thank you very much for the post. I will be looking forward for post in which you will mention how to fetch email id also.

    and most desirable are the video lectures from you.

  25. Anonymous says:

    Hey Nick, did you ever get a chance to figure out the logout yet?

  26. @All – I just published a new post:

    'Get User's Email Address from Facebook with ASP.net Web Forms'

    blogs.msdn.com/…/get-user-s-email-address-from-facebook-with-asp-net-web-forms.aspx

  27. Anonymous says:

    When i ran your sample only Id property is populated with data and rest other are emtpy. When i debugged the local host code i found that Response from facebook contains only value for Id and rest other values are not showing in response object . Although I have created App on facebook and updated the AppId and SecretId in the config file .

    Is there anything I need to verify which is causing issue.

    Thanks,

  28. @Amit – I would recommend first trying another Facebook account or creating a test account via the Facebook Developer Portal.  If that doesn't provide you with full profile information in the response then you may also want to try creating a new Facebook App within the portal and trying again.  Let me know how you make out.

  29. Anonymous says:

    Hi Nick

    Excellent article and example.

    I'm however facing the exact same issue as Amit, whereby only the "ID" property is populated from Facebook.

    Do you perhaps know what could be causing this behavior?

    Regards

    JohannS

  30. @Johann – Thank you!  I just ran a test with my Facebook account as well as a new Test account from the Facebook Developer Portal and all ran successfully.  Can you try creating a new Facebook App in the Developer Portal, updating the App Id and App Secret in the web.config and trying again.  Please let me know how you make out.

  31. José Dalri says:

    Hi, nice work in this post!

    I'm having the same problems as Johan…

    My JSON result only has my name and id, and when it deserializes,

    the only information that is left is the id…

    I've tryed with a different account, but the same happens.

    Do you have any ideia of why this is happening?

    Thanks in advance.

  32. @Amit, @Johann, @José – I had a chance to research your issue and have resolved it.  Simply re-download the project from GitHub, add your App Id and App Secret and run the project.

    On July 8th Facebook introduced v2.4 of the Graph API.  With this new version they reduced the number of fields that the API returns by default.  This was done in the effort to improve performance on mobile network connections.  Therefore you must now declare all the fields you want the API to return.  This can be found in user.aspx.cs of the project:  graph.facebook.com/me?fields=first_name,last_name,gender,locale,link .  Thank you for notifying me of the issue 🙂

  33. Lokesh Paliwal says:

    Nick, its very nice article. And its really helpful.

    Thanks 🙂

  34. Ken Nelson says:

    Thanks a lot. Worked great and is very clear and simple.

    I presume something very similar could be used to login with Google?

  35. @Ken – Correct, the same process would be used to login with Google.  They both use the OAUTH 2.0 standard.

  36. @All – I just published a new post:

    'Publish to Facebook with ASP.net Web Forms'

    blogs.msdn.com/…/publish-to-facebook-with-asp-net-web-forms.aspx

  37. SimorC says:

    Thanks, this is going to be useful for my college projects.

  38. Jubbs says:

    Hi Nick, thanks for this tutorial. Please forgive my ignorance but I'm struggling with this concept. I have this running fine in my webapp – it tells me that I'm logged in with FB and shows my FB details in listview1.  The problem is that my site does not recognise that a user is logged in, i.e. HttpContext.Current.User.Identity.IsAuthenticated returns a false value. How do I tell my app that the user is logged in, with User Name "Facebook_User_Primary_Email_Address"?

  39. @Jubbs – You're very welcome.  That's a great question.  This tutorial solely covers the process of Facebook Login and not subsequent authentication into your web app.  I will however be covering this topic in a chapter of an eBook / Book I am releasing at the beginning of 2016 entitled 'Facebook Development with ASP.NET and Microsoft Azure'.  There I cover how to programmatically create a session using Forms Based Authentication once a user has passed Facebook Login.  This will then place your user in the context of a current user in ASP.NET.  In the meantime you can follow me on Twitter to be notified once the eBook is available.  I will also be releasing an email subscription list in the next few days that you can subscribe to as well.

  40. Madhu says:

    Hi Its working fine in my local system, but when i host in server it display 404 error bad request what to do

  41. @Madhu – Once you publish the code to your server you will need to go to developers.facebook.com and change your 'Site URL' to the URL of your web app on the server.  

  42. @developerchick – I have a working sample for Logout.  Let me know if you still need assistance with this.

  43. Madhu says:

    Hi Nick I have already Updated SiteURL(www.goresults.net/fb) but still i am getting same issue – runtime error bad request Please check http://www.goresults.net/fb -( Fb virtuval direcory) there register button is on top of the website – Please suggest me thankyou for your quick response

  44. Madhu says:

    Still Not Working Nick Please Help Me

  45. kubera says:

    @madhu you will have that problem if page is refreshed.. i got the error when i refreshed user.aspx

    Line 37:             System.IO.StreamReader str = new System.IO.StreamReader(at.GetResponse().GetResponseStream());

  46. BonDev says:

    Hello how can i save that user's information to sql server 2008, im a newbie so i dont know

  47. @Madhu – I'm not seeing your implementation at http://www.goresults.net/fb.  Please advise.

  48. @BonDev – The easiest way to store that information in SQL Server would be to use ADO.NET.  The following is a link with sample code for ADO.NET:  msdn.microsoft.com/…/dw70f090(v=vs.110).aspx

  49. itzzz says:

    thanks…..it is very helpfull

  50. Hello All! Join my just released mailing list for free content, videos, blog posts, webinars, eBooks and more! http://www.nick-pinheiro.com

    1. tam says:

      hi,i like all the above

  51. Romeo A. says:

    Thank you.
    Clear and simple.

  52. Ben says:

    Thank you for this write up. Sent several days trying to create an OAuth plugin, this helped me get over my final issues.

  53. umara says:

    you are a life saver :p thanks a ton very simple explanation (y) now gonna try it…

  54. Kishor Khatri says:

    Thank You so much, it worked for me, i was facing problem since 7 days.

  55. Harshal says:

    thank you so much sir,
    i found it the best.
    awesome and simple explanation

Skip to main content