Tuesday, June 3, 2014

Authenticating Users via Facebook in ASP.NET MVC 4

This section shows you how to build an ASP.NET MVC 4 application that enable users to log in with external providers like Facebook. The same way you can authenticate users using Google, Twitter, etc…
The following describes the steps to follow.

In Visual Studio, create a new ASP.NET MVC 4 web application and name it as ‘FB’. Select the target framework as 4.5 or 4.

Select ‘Internet Application’ as the project template.
In the selected project template, the project is created with a file named AuthConfig.cs in the App_Start folder. This file contains code to register for external authentication providers. By default, the code segment is commented.

 


















Since we are going to authenticate users using Facebook, uncomment the section that represent Facebook authentication.

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: "",
                appSecret: "");

            //OAuthWebSecurity.RegisterGoogleClient();
        }
    }

The above code required for two parameters; appId and appSecret. If you try to run the application now, the application will throw exception. You need to give valid parameters, to provide the values, you must register your web site with Facebook.

Registering the web site with Facebook

You must register with the provider to get the required parameters. Visit Faceebook Developer page and click ‘Create a New App’ link under Apps to create a test app.


















Give Display Name, Namespace and click ‘Create App’ button.
Go to settings tab of the created App, you will find the App ID and the App Secret.















While registering you need to provide MVC application hosting URL to Facebook App (in my case localhost). You can give the URL by clicking ‘Add Platform’ link.

As the final step add the appId and appSecret to AuthConfig class and you have done. Run your application and click in Log in button.

The template automatically includes the button to log with Facebook.













You can click on the Facebook button, which will redirect to Facebook login page.













Once you log in using Facebook credentials, you can see the home page of the MVC application with the Facebook user.