Skip to main content

Authenticate your ASP.NET MVC WebSite using Facebook

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.

Comments

Popular posts from this blog

Creating package in Oracle Database using Toad For Oracle

What are Packages in Oracle Database A package is  a group   of procedures, functions,  variables   and  SQL statements   created as a single unit. It is used to store together related objects. A package has two parts, Package  Specification  and Package Body.

Resolving 'Setup Account Privileges' error while installing SQL Server

A new installation of Microsoft SQL Server 2012 or Microsoft SQL Server 2008 R2 fails You see the following error message when you try to install a new instance of SQL Server 2012 or SQL Server 2008 R2: Rule "Setup account privileges" failed.

Creating Oracle stored Procedures using TOAD for Oracle

In a database management system, a  stored procedure  is a set of Structured Query Language (SQL) statements with an assigned name that's stored in the database in compiled form so that it can be shared by a number of programs. The use of  stored procedures  can be helpful in controlling  access to data, preserving  data integrity  and  improving  productivity.