For those of you who read our blog on Social Media Authentication about 4 weeks ago (I hope you all did and found it interesting), you might remember how I introduced the concept of a single social identity and how some of the bigger social media networks such as Facebook, Twitter and Google+ have all integrated the OAuth 2.0 framework so as to allow us developers to get public information from our clients' profiles (with their authorization of course). This would help us make it much easier for our users to signup onto our websites without having to create a whole new profile again and remember a new password every time they register on any of our websites. I had also introduced the DotNetOpenAuth framework specifically designed to allow .Net developers to integrate the OAuth framework with their sites using a very simple API. If you feel like you need to refresh your memory about how we can exchange secret keys with the OAuth framework in order to get a code which we exchange for a token to access the users information, I would suggest that you take a look once more at my previous blog. (Don't feel bad if you don't, I had to read it again so as to make sure I don't repeat myself in this blog)

In my previous blog I had promised you that I will show you using examples of how we can implement a security layer which would allow us to authenticate the users using DotNetOpenAuth api and today I intend to do just that. I will explain how we can do this using both the MVC 3 and MVC 4 frameworks. (The reason Im pointing this out is that many developers still have websites implemented in MVC 3 and for some reason or another it wouldn't be feasable to migrate your solution to MVC 4. This however, should not stop you from updating your website and integrating social media authentication on your platform.)

I intend to show you how this can be done using Facebook and we will use a good Facebook library in order to authenticate our users on the Server Side. You will find several examples and implementations how one can integrate Facebook authentication on the client side, however for backend gurus such as myself who prefer handling code (and exceptions) on the server side, I will show you examples of how you can do this in the 'code behind' and retrieve the clients information using some simple api calls using this library.

Using MVC 3.0 in Visual Studio 2010

Unfortunately in MVC 3, facebook integration was still being done manually, and in some cases before some decent Facebook Client libraries came out, we had to do most of the code on the client side and then exchange the information on the server side and store the data on our databases as we please. However in the last year or so, some providers have released decent Facebook SDKs for .NET which simplified our work a great deal.

To start off first of all you would need to create a Facebook application for your website and get the AppId and Secret Key provided by Facebook. If you don't remeber how to do this, please have a look at my previous blog on Social Media Authentication.

After that you need to install the Facebook C# SDK using the nuget package. You can see how this can be done by following the steps on the following link: http://facebooksdk.net/docs/web/getting-started/.

Next you should create a new MVC project and create the following:

View: 

  • Index.cshtml
  • Info.cshtml

Controllers:

  • Account Controller.cs
  • HomeController.cs

Model:

  • InfoModel.cs

 In the web config, you should create two keys, for the AppId and for the SecretKey as shown below:

<add key="Facebook_AppID" value="YOUR APP KEY" ></add>
<add key="Facbook_SecID" value="YOUR APP SECRET KEY" ></add>

 In the Index.cshtml page, add some simple code with a Facbook login button where the action would post to a LoginFb action which would send a request to facebook to retrieve a code with the user's permission and then use the code to retrieve a token.

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2> @Html.BeginForm("Loginfb","Account")     {            <input type="submit" value="Login Using Facebook" id="saveButton"/>     }

 The Info.cshtml page would be used to display the user's information retrieved. A simple way to put the view should look somthing like this:

@model PostIt.Models.InfoModel
@{
    ViewBag.Title = "Info";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Your Information</h2>
Firt Name : @Html.DisplayFor(v => Model.firstName);
<br /><br />
Last Name : @Html.DisplayFor(v => Model.lastName);
<br /><br /> Email : @Html.DisplayFor(v => Model.emailId); @{     using (Html.BeginForm("LogOut", "Account", new {Model.accessToken}))     {         <input type="submit" value="Logout" id="Button"/>     }     }

The InfoModel should contain the following fields as shown below:

    public class InfoModel
    {
        public string accessToken { get; set; }
        public long fbId { get; set; }
        public string firstName { get; set; }
        public string lastName { get; set; }
        public string emailId { get; set; }
    }

 Now that we have the model and the views set up, we move to the interesting stuff.

The AccountController.cs is responsible for making a facebook request to the user using the ApplicationId, and if the user accepts, we recieve the code and redirected to the HomeController.cs as shown below.

public class AccountController : Controller
    {         //         // GET: /Account/         private static readonly string SecId = ConfigurationManager.AppSettings["Facbook_SecID"].ToString();         private static readonly string AppId = ConfigurationManager.AppSettings["Facebook_AppID"].ToString();

        public ActionResult Loginfb()         {             var redirectUri = new UriBuilder(Request.Url);             redirectUri.Path = Url.Action("Info", "Home");
            var client = new FacebookClient();             var uri = client.GetLoginUrl(new             {                 client_id = AppId,                 redirect_uri = redirectUri.Uri.AbsoluteUri             });           
            return Redirect(uri.ToString());         }                  public ActionResult LogOut(string accessToken)         {             var oauth = new FacebookClient();             var logoutParameters = new Dictionary<string, object>                   {                      {"access_token", accessToken},                       { "next", "http://localhost:8691" }                   };
            var logoutUrl = oauth.GetLogoutUrl(logoutParameters);             return Redirect(logoutUrl.ToString());         }     }

The HomeController.cs on the other hand will contain code which initializes the FacebookClient (a class part of the Facebook SDK) which would be use the code received from Facebook to get the token and make requests using the token and retrieve the user's information. 

The Home controller should look something like this:

public class HomeController : Controller
    {
        //
        // GET: /Home/
        private static readonly string SecId = ConfigurationManager.AppSettings["Facbook_SecID"].ToString();
        private static readonly string AppId = ConfigurationManager.AppSettings["Facebook_AppID"].ToString();

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Info()
        {
            var client = new FacebookClient();
            var oauthResult = client.ParseOAuthCallbackUrl(Request.Url);

            // Build the Return URI form the Request Url
            var redirectUri = new UriBuilder(Request.Url);
            redirectUri.Path = Url.Action("Info", "Home");

            // Exchange the code for an access token
            dynamic result = client.Get("/oauth/access_token", new
                         {
                            client_id = AppId,
                            redirect_uri = redirectUri.Uri.AbsoluteUri,
                            client_secret = SecId,
                            code = oauthResult.Code,
                                                                   });

            // Read the auth values
            string accessToken = result.access_token;
            Session["access_token"] = accessToken;
            DateTime expires = DateTime.UtcNow.AddSeconds(Convert.ToDouble(result.expires));
            // Get the user's profile information             dynamic me = client.Get("/me",                                     new                                         {                                             fields = "first_name,last_name,email",                                             access_token = accessToken                                         });
            var userInfo = new InfoModel()                                {                                    firstName = me.first_name,                                    lastName = me.last_name,                                    emailId = me.email,                                    accessToken = result.access_token                                };             return View("Info", userInfo);         }     }

 The oauthResult gives us the code, we then use the code, the Appid, the AbsoluteUri and the Secret key to get the token. Using the Facebook SDK we can then use the token in the client (passed as a constructor) and get any information we want from the client using the 'Client.Get' method. As you can see we are using a dynamic object to store the JSON result from the Facebook Client and then get all the information we need about the user.

Thats it! You can than store the user's information as you wish and authenticate the user using the user's FacebookId whenever you want to check if he is a registered or a new user.

For those of you who have already migrated to MVC 4.0 (we will do a blog about the new features introduced in the new MVC farmework in the future) and are obviously using Visual Studio 2012, it is now very simple to authenticate a user using the OAuth 2.0 framework which comes integrated in the MVC 4.0 package and Microsoft were even nice enough to create a project template initializing all the classes, datastores and configurations for us to do so. 

All you have to do in MVC 4.0, is create a project on VS 2012, and initialize the AppId and Secret keys in the AppSettings section in the web config as explain above. A class called AuthConfig.cs has been already created under the App_Start folder conatining code for registrations on various platforms. All you need to do is uncomment the OAuthWebSecurity.RegisterFacebookClient code in order to activate Facebook registration as shown below:

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(); } }

 Retrieve the homepage URL of the application by running the application or setting it up on the IIS, and update the URL in the Facebook App you have created. Run the App and follow the steps provided by Facebook. From there on its simple trivial steps. Facebook will associate your App with the Facebook Account and in your default database connection it will store the Provider, ProviderUserId and UserId. If you open your data connections you will see your default connection and the OAuthMembership tables. All these are created automatically thanks to the SimpleMemberShipProvider provided to us in the new MVC 4.0 framework.

For a detailed tutorial and a very good example on how to integrate an MVC 4.0 solution with Facebook authentication, please take a look at the following link. The blog contains a great example of how to use MVC 4.0 and VS 2012 templates to integrate Facebook Authentication on your website. 

In this blog I felt it was more important to explain how to integrate Facebook Authentication with MVC 3.0 as you don't find a lot of good examples out there, the main reason being that everyone is migrating to MVC 4.0 and rightly so, however its important not to sideline our old websites. Updating your website continuously is vital if you want your users to keep on coming back again. Make sure you're using the latest standards and technologies so as to make it as easy as possible for your clients to come back over and over again and have a pleasant experience while browsing your web site.

 

Thanks for reading

Shaun