Freigeben über


Facebook Login with ASP.NET Web Forms

Join my mailing list!

01/04/18 - Facebook Login should now be implemented using the new 'Facebook Solution Framework (FSF) NuGet Package for .NET'.   Documentation for the NuGet Package can be found at:
https://www.modernappz.com/products/fsf/nuget/

 

02/28/15 - 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

  • Anonymous
    April 01, 2015
    Thank you very much

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

  • Anonymous
    April 09, 2015
    @developerchick - Glad it worked for you :)  In terms of logging out... are you referring to logging the user out of your application or Facebook?

  • Anonymous
    April 09, 2015
    @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.

  • Anonymous
    April 09, 2015
    @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.

  • Anonymous
    April 09, 2015
    @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.  

  • Anonymous
    April 09, 2015
    @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.

  • Anonymous
    April 09, 2015
    @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?

  • Anonymous
    April 09, 2015
    @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.

  • Anonymous
    April 09, 2015
    @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?

  • Anonymous
    April 09, 2015
    @Nick - forget it, found some old code I had forgotten to un-comment.  My fault! :)  Let me know about the logout.  Thanks again!

  • Anonymous
    May 04, 2015
    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.

  • Anonymous
    May 04, 2015
    @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/'.  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.

  • Anonymous
    May 05, 2015
    @Nick - I followed your instructions, but there's still that error @@

  • Anonymous
    May 05, 2015
    @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

  • Anonymous
    May 05, 2015
    @Nick - I sent an email to you. Thank you.

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

  • Anonymous
    May 11, 2015
    @Xchange - Please ensure that your 'FacebookAppId' and 'FacebookAppSecret' are entered properly in the web.config.

  • Anonymous
    May 17, 2015
    Thanks bro..nice and simple

  • Anonymous
    June 02, 2015
    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 :)

  • Anonymous
    June 02, 2015
    @Robin - Have you first been able to get the solution to work within Visual Studio?

  • Anonymous
    June 07, 2015
    @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... :(

  • Anonymous
    June 08, 2015
    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?

  • Anonymous
    June 16, 2015
    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.

  • Anonymous
    June 22, 2015
    Hey Nick, did you ever get a chance to figure out the logout yet?

  • Anonymous
    July 07, 2015
    @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

  • Anonymous
    July 09, 2015
    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,

  • Anonymous
    July 13, 2015
    @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.

  • Anonymous
    July 13, 2015
    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

  • Anonymous
    July 13, 2015
    @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.

  • Anonymous
    August 11, 2015
    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.

  • Anonymous
    August 13, 2015
    @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 :)

  • Anonymous
    August 27, 2015
    Nick, its very nice article. And its really helpful. Thanks :)

  • Anonymous
    September 04, 2015
    Thanks a lot. Worked great and is very clear and simple. I presume something very similar could be used to login with Google?

  • Anonymous
    October 23, 2015
    @Ken - Correct, the same process would be used to login with Google.  They both use the OAUTH 2.0 standard.

  • Anonymous
    October 28, 2015
    @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

  • Anonymous
    October 31, 2015
    Thanks, this is going to be useful for my college projects.

  • Anonymous
    November 21, 2015
    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"?

  • Anonymous
    November 23, 2015
    @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.

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

  • Anonymous
    November 29, 2015
    @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.  

  • Anonymous
    November 30, 2015
    @developerchick - I have a working sample for Logout.  Let me know if you still need assistance with this.

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

  • Anonymous
    January 05, 2016
    Still Not Working Nick Please Help Me

  • Anonymous
    January 09, 2016
    The comment has been removed

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

  • Anonymous
    January 20, 2016
    @Madhu - I'm not seeing your implementation at www.goresults.net/fb.  Please advise.

  • Anonymous
    January 20, 2016
    @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

  • Anonymous
    February 26, 2016
    thanks.....it is very helpfull

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

    • Anonymous
      June 13, 2016
      hi,i like all the above
  • Anonymous
    April 20, 2016
    Thank you. Clear and simple.

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

  • Anonymous
    May 02, 2016
    you are a life saver :p thanks a ton very simple explanation (y) now gonna try it...

  • Anonymous
    July 14, 2016
    Thank You so much, it worked for me, i was facing problem since 7 days.

  • Anonymous
    August 21, 2016
    thank you so much sir,i found it the best.awesome and simple explanation