Using Facebook to Authenticate your ASP.NET MVC WebSite

Posted by: Suprotim Agarwal , on 3/25/2013, in Category ASP.NET MVC
Views: 57031
Abstract: This article demonstrates how to use Facebook Authentication for your ASP.NET MVC Web Application

ASP.NET MVC team recently integrated the excellent open source library called DotNetOpenAuth (DNOA). DotNetOpenAuth originally was created to add OAuth and OID Authentication capabilities. The library bakes in functionality to let your application to be an OAuth Server or an OAuth client (or both).

Thanks to the integration efforts by the ASP.NET team, integrating DNOA to use an external Open Auth or OID provider is now as easy as un-commenting a few lines of code and registering yourself with the Provider.

Today we will do just that. Given the popularity of Facebook, a vast majority of people have Facebook accounts and if we can use Facebook to authenticate people on our website, we make it easier for the user by not requiring them to remember an additional password for our site.

 

Getting Started as a Facebook Developer

If you have a Facebook account already, you’ll need to verify it by either providing your Credit Card or Telephone Number. If you are using a phone number the phone should be capable of receiving SMS (Text messages). With this pre-requisite handy, let’s get started.

1. Navigate to https://developers.facebook.com/ and log in with your Facebook ID

facebook-developer-toolbar

2. If you don’t have a verified account, on login to the dev portal, Facebook will ask you to verify the account using Credit Card or Phone number. As mentioned above, they will text you a verification code if you are using the phone number. Put in the code and you are good to go. You should see the above bar at the top of the page.

Registering a Facebook App

Now that we are logged in as Facebook developers, let’s setup an App so that we can leverage it in our own Web Site.

1. Click on Apps in the toolbar, Facebook will show the type of apps you can build for it.

facebook-application-types

2. As we can see above, the Websites option is what we are looking for. Click on ‘Create a New App’ you’ll get the following popup

create-new-facebook-app

3. Pick a Name and a Namespace (though mentioned as optional, provide it here). You can leave the Web Hosting unchecked. Click Continue. Fill in the captcha and you will end up on the configuration page as follows.

facebook-app-settings

  • a. First thing to note above is the App ID and App Secret. These two link your App to Facebook. We will use these shortly
  • b. Next expand the Website with Facebook Login field. It is empty currently. We have to come back to it once we have our WebApplication ready.

Now that we are nearly all set with the Facebook App, let’s shift focus to the ASP.NET App and hook the two together.

Creating a new MVC4 Web Application and hooking it up with the Facebook App

1. We start off with the a new MVC4 project in Visual Studio and name it MVC4FacebookAuthentication

2. Next we add two entries in <appSettings> section of our Web.config. These are appId and appSecret. Copy pastes the values from the Facebook Settings Page

app-id-

3. Secret Next we open the AuthConfig.cs file under App_Start folder and uncomment the RegisterFacebookClient line. We replace the empty values with the values loaded from Web.Config using the ConfigurationManager. And that’s all the configuration that’s required.

public static class AuthConfig
{
public static void RegisterAuth()
{
  // To let users of this site log in using their accounts from other sites such as Microsoft, Facebook, and Twitter,
  // you must update this site. For more information visit
http://go.microsoft.com/fwlink/?LinkID=252166

  //OAuthWebSecurity.RegisterMicrosoftClient(
  //    clientId: "",
  //    clientSecret: "");

  //OAuthWebSecurity.RegisterTwitterClient(
  //    consumerKey: "",
  //    consumerSecret: "");

  OAuthWebSecurity.RegisterFacebookClient(
   appId: ConfigurationManager.AppSettings["AppId"],
   appSecret: ConfigurationManager.AppSettings["AppSecret"]);

  //OAuthWebSecurity.RegisterGoogleClient();
}
}

4. Run the app and retrieve the home page URL

site-url-to-be-used

5. Go back to the Facebook App Settings page and update the “Site URL” with the above URL. Save the settings. When we move the application to production, we’ll have to update the “Site URL” in the Facebook app to match our production URL.

updated-site-url-in-facebook-app

6. Once the Facebook settings are saved, switch back to the ASP.NET web application and click on Login to navigate to the following page:

mvc4-app-login-screen

7. Click on the ‘Facebook’ Service login button. It will navigate you to the following page.

facebook-developer-login

8. Facebook is telling the end user that they are using their Facebook account with ‘DNCWebTest’ (our application). Once you log in, for the first time you’ll get the following confirmation dialog.

giving-permissions-to-fb-auth

Note that the DNCWebTest app by default has only access to basic info and email address of end user. Once the user clicks “Go to App”, Facebook re-directs back to our app.

When we are logging in for the first time, the Membership provider detects that it’s the first login and registers the new user and requests the user to provide a User name. As we can see below, it uses the email ID provided by Facebook by default

first-time-registration-after-fb-auth

9. The user clicks on Register to link their User name with the Facebook Id that they used to log in with. This Registration page does not come up again. Once the Registration information has been saved, user will be redirected back to the home page where they are now authenticated using Facebook

facebook authenticated

Under the Hood - The SimpleMemberShipProvider

All this seemingly magical integration is possible; thanks to the new SimpleMemberShipProvider which is now the default MemberShipProvider for ASP.NET MVC4 Internet Projects. Let’s look a little deeper. We start off with the database

1. Open the Web.config and find the DefaultConnection entry in ConnectionStrings section. It will look similar to the following

<connectionStrings>
    <add name="DefaultConnection"
         connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-Mvc4FacebookAuthentication-20130322131534;
         Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-Mvc4FacebookAuthentication-20130322131534.mdf"
         providerName="System.Data.SqlClient" />
  </connectionStrings>

The connection string doesn’t really have anything to do with the provider. It simply uses an instance of (LocalDb) by default and uses a Database Name generated by Visual Studio when the project was created.

This however becomes the connection information that is used out of the box. Initially the database is of course empty. But on first Registration or login request, a set of tables are created by the Membership Provider using this connection information.

2. Let us see what these tables are. Open the Database Explorer and refresh the ‘DefaultConnection’ node. Expand the tables to see the tables created by SimpleMemberShipProvider after the first run.

simple-membership-provider-schema

3. Right click on the UserProfile table and select Show Table Data. As you can see the, UserName registered by the user is stored in the UserProfile table.

simple-membership-provider-oauth-table

4. Next select the webpage_OAuthMembership table, right click on it and select Show Data. This shows the ProviderName and an ID value returned by Facebook that is unique for each user who authenticates. This is tied back to the UserProfile table using the UserId Foreign Key reference.

5. This is the basic amount of data that SimpleMembershipProvider stores when authenticating with one of the external services using OAuth

Conclusion

This concludes this post on using Facebook Authentication for your ASP.NET Web Application. It assumed you (as a developer) have a Facebook login already. If not, go ahead and create an account and then create a Developer profile as explained above.

In future episodes, we will see how to retrieve information from Facebook after you have logged in using Facebook Authentication.

Download the entire source code of this article (Github)

Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles
Suprotim Agarwal, ASP.NET Architecture MVP, MCSD, MCAD, MCDBA, MCSE, is the CEO of A2Z Knowledge Visuals Pvt. He primarily works as an Architect Consultant and provides consultancy on how to design and develop .NET centric database solutions.

Suprotim is the founder and primary contributor to DotNetCurry, DNC .NET Magazine, SQLServerCurry and DevCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls. and is authoring another one at The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by Nava on Monday, March 25, 2013 5:30 AM
So can I use this without creating an account and get more information like email etc?
Comment posted by Sumit on Monday, March 25, 2013 10:57 AM
Nava,
I didn't understand the context of this statement - 'without creating an account'.

If you are referring to Step 8 (second image) above, then Email + authentication token + Facebook UserId are the only things that you will get from Facebook. To get more information you have to use dedicated Facebook API (and also tweak your App Setting in Facebook depending on the information you need).

Let us know if I got the question wrong.
Thanks and Regards,
Sumit.
Comment posted by Suprotim Agarwal on Wednesday, March 27, 2013 7:12 PM
You can get a user’s name, personal pages, Verification details but you need to log in. To get this info you can either store the user data that can be accessed during the authentication request or call the provider API and request more information
Comment posted by Jack Walsh on Sunday, May 5, 2013 2:15 PM
"In future episodes, we will see how to retrieve information from Facebook after you have logged in using Facebook Authentication."

- I eagerly look forward to this part, as I'm sure others are interested as well. I guess the real question is how to use the dedicated FB API to get additional info such as birthday, to post to the user's wall, etc. Thanks!
Comment posted by sucharita ghosh on Thursday, May 23, 2013 6:55 AM
I want that when a viewer wants to register in my website ,he/she can do that by only login into facebook.I have created facebook aap id and secret code.What will be the code in c# to implement this process..If anybody knows then please share
Comment posted by sucharita ghosh on Thursday, May 23, 2013 6:57 AM
and also tell how the facebook information of the user like birthdate,gender,name,address will be shown in my website page.
Comment posted by Emanuel on Tuesday, June 11, 2013 10:50 PM
I'm very interested in the followup too. I'd like to get the user's birthdate, gender, address, and picture would be great.
Comment posted by 'neeraj on Monday, July 29, 2013 3:27 PM
nice tutorial really help me in developing in mvc4 login system
Comment posted by Jack Owens on Sunday, August 4, 2013 1:26 PM
Suprotim,

FYI - You have tried to hide your email very well in most of the screens but for Screen # 4 (i.e. in Section # 3)

You might want to change that screen?
Comment posted by digish on Monday, September 2, 2013 12:28 PM
thanks.
Comment posted by sampath on Friday, October 11, 2013 8:46 AM
Clean and clear explanation.Thanks for sharing.But one problem is which your code snippets are not showing color for the code syntax.So if you can correct it,it'll help for our readability.
Comment posted by Suprotim Agarwal on Tuesday, October 15, 2013 2:48 AM
Thanks Sampath for your suggestion. The site is undergoing various changes and one of them is code syntax highlighting. We have given ourselves a deadline of Jan 2014 :)

Jack Owens: Thanks Jack, yeah looks like I missed out on that one!
Comment posted by Jack on Tuesday, July 1, 2014 2:00 PM
Hi,
Thanks for the article, is it possible to achieve the same in Asp.Net 4.0 Web forms? Also what happens with the regular membership database now?

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel