BlueLemonCode.Com

Yet Another Tech Blog

Using Facebook plugin for user registration on your web site

 Introduction

There are many Facebook plugins available which could be useful based on what is required. Out of these Facebook Registration plugin is something would help service oriented web sites to encourage visitors to register on their site.

We are going to see little about the way to use registration plugin in asp.net web sites.

Background

For small, service oriented web sites it is required that their visitors register themselves onto their web site. Consider a local movie hall provides a facility to book the movie ticket. For web sites like simillar services, it is required that visitors register themselves so that they can track their choices, mailing list, promotional offers etc.

However, at times it becomes difficult to get people do the registerration. I would personally hate the web site who asks me to fill up the form before i can book a movie.

On the other side, majority of people would have a Facebook account. Though, i know there are people who pretend to hate the Facebook (i think they would still have a secret facebook account ;) .

So, how if users dont have to fill up that stupid registration form on your website? Rather, they would login to their facebook account from your site and it would give the required user details to your site. That way, you get all the required details which you need to register the user and user dont have bother about filling up the form.

Article Body

Ok. Let me start me by saying.. The steps provided below are referenced from Facebook developers guide. If you want refer to documentation, please go to https://developers.facebook.com/docs/plugins/registration/.

My attempt here is to simplify the explaination for specifically Asp.Net developers.

To use Facebook registration plugin on your site, we need to follow below steps

  • Register URL of your website registration on Facebook.
  • Use either IFRAME tag or XFMBL tag or Javascrip SDK on your site which will manage to display Facebook registration link and redirect user to FB login and then return the response with all required data in the form of JSON object
  • Read the returned JSON data and decrypt it and then use it to register user in your site

First of all, to use facebook registration plugin on your site we need to register URL of your site on FB. Go to Facebook Apps developer page here. You will have to provide your Facebook authentication in order to continue. Then, go to "Create New App" section on top right corner of the page.

Name your App and namespace, agree to FB policies (after reading) and you will reach to below page. I named my App as BlueLemonCode

Note the higlighted area which reads website. We will have to provide the URL of the page where we are going to place Registration plugin. As, we are running the demo from localhost, we will provide the localhost URL.

before that, we will have to create a website on localhost. We would come to this step after some time.

Now, lets start by creating a demo project in asp.net. I am using VS 2008 to create this demo.

I create a new asp.net web site and run it with empty page first so that i can get a URL. I come up with the URL

http://localhost:51951/FBRegistrationPlugin/Default.aspx

Now, go to Facebook Apps page again and provide this URL in website section.

Back in your default.aspx page, I am going to use IFRAME tag provided by FB (you might want to try with, XFBML or Javascript SDK. Plz visit this link)

<iframe src="https://www.facebook.com/plugins/registration.php?
             client_id=xxxxxxxx&
             redirect_uri=http://localhost:51951/FBRegistrationPlugin/Default.aspx&fields=name,birthday,gender,email"
        scrolling="auto"
        frameborder="no"
        style="border:none"
        allowTransparency="true"
        width="100%"
        height="330">
</iframe>

You will have change the client id and redirect uri as per your setting. Client ID for your is nothing but App id and it can be found at header of App registration page.

In the redirect uri link, fields are specified. These are the fields which you want FB to return to you after user authentication. Apart from fields used in above code, Password and captcha are the fields which FB can return to your website (Plz note that Password is not the FB password rather, separate password which FB will additionally ask users to enter. This can serve as password for your website)

Now the half part is complete. How about the response from Facebook? although we have provided redirect url which indicates the url of your website where users will be sent back from FB page.. but their is a catch. The response would be signed using your App secret id and we will have to write a code to decrypt the response before you can make a meaning out of it.

Please note that the response is a JSON object with fixed format. The example format has been provided on FB. I am providing it below for quick reference.

{
   "oauth_token": "...big long string...",
   "algorithm": "HMAC-SHA256",
   "expires": 1291840400,
   "issued_at": 1291836800,
   "registration": {
      "name": "Paul Tarjan",
      "email": "fb@paulisageek.com",
      "location": {
         "name": "San Francisco, California",
         "id": 114952118516947
      },
      "gender": "male",
      "birthday": "12/16/1985",
      "like": true,
      "phone": "555-123-4567",
      "anniversary": "2/14/1998",
      "captain": "K",
      "force": "jedi",
      "live": {
         "name": "Denver, Colorado",
         "id": 115590505119035
      }
   },
   "registration_metadata": {
      "fields": "[\n {'name':'name'},\n {'name':'email'},\n {'name':'location'},\n {'name':'gender'},\n {'name':'birthday'},\n {'name':'password'},\n {'name':'like',       'description':'Do you like this plugin?', 'type':'checkbox',  'default':'checked'},\n {'name':'phone',      'description':'Phone Number',             'type':'text'},\n {'name':'anniversary','description':'Anniversary',              'type':'date'},\n {'name':'captain',    'description':'Best Captain',             'type':'select',    'options':{'P':'Jean-Luc Picard','K':'James T. Kirk'}},\n {'name':'force',      'description':'Which side?',              'type':'select',    'options':{'jedi':'Jedi','sith':'Sith'}, 'default':'sith'},\n {'name':'live',       'description':'Best Place to Live',       'type':'typeahead', 'categories':['city','country','state_province']},\n {'name':'captcha'}\n]"
   },
   "user_id": "218471"
}

To make the JSON conversion easy, I am creating a class structure of data which i am expecting in response object. As it is evident from the JSON format above, registration class would contain fields like name, gender, birthday and email. While, main response class would contain, algorithm field, registration class object etc.

Also, we would need to take care of converting response string from binary data as base 64 to 8 bit unsigned integer array. To complete this task, I am going to use Convert.FromBase64String(string) method available in .Net. You can read more about this method here.

The complete c# code is below. You can simply copy and paste below code in your asp.net project

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Web.Script.Serialization;
public class FBData
{
    public string name { get; set; }
    public string birthday { get; set; }
    public string gender { get; set; }
    public string email { get; set; }
}
public class FBResponse
{
    public FBData registration { get; set; }
    public string algorithm { get; set; }
}
public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.Form["signed_request"] != null)
        {
            string strName = string.Empty;
            string strBirthday = string.Empty;
            string strGender = string.Empty;
            string strEmail = string.Empty;

            string[] requestArray = Request.Form["signed_request"].ToString().Split('.');
            string dataString = base64Decode(requestArray[1]);

            JavaScriptSerializer js = new JavaScriptSerializer();
            FBResponse fb = js.Deserialize<FBResponse>(dataString);
            strName = fb.registration.name;
            strBirthday = fb.registration.birthday;
            strGender = fb.registration.gender;
            strEmail = fb.registration.email;
            string message = "<p><font size=\"3\" font-face=\"verdana\"> User registration completed! The following details are updated from your Facebook account. <br/>Please modify these details if required </p>";
            Response.Write(message);
            Response.Write("<br/>");
            Response.Write("Name    -   " + strName + "<br/>");
            Response.Write("Birtday -   " + strBirthday + "<br/>");
            Response.Write("Gender  -   " + strGender + "<br/>");
            Response.Write("Email   -   " + strEmail + "<br/>");
            FBReg.Visible = false;
        }
    }

    public static string base64Decode(string data)
    {
        data = data.Replace("-", "+").Replace("_", "/");        
        //length of string needs to be in multiple of 4 so that it can be converted to base 64 string
        if (data.Length % 4 != 0)
        {
            while (data.Length % 4 != 0)            
                // character '=' is valueless and used for trailing padding
                data = data + "=";            
        }
        byte[] binary = Convert.FromBase64String(data);
        return Encoding.UTF8.GetString(binary);
    }
}

And below is the code for default.aspx

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" EnableEventValidation="false"%>

<%@ Register Assembly="DotNetOpenAuth" Namespace="DotNetOpenAuth.OpenId.RelyingParty"
    TagPrefix="rp" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">

    <title></title>
</head>
<body>
    <form id="form1" runat="server">

    <div id="FBReg" runat="server">
    <iframe src="https://www.facebook.com/plugins/registration.php?
             client_id=271666629543944&
             redirect_uri=http://localhost:51951/Test/Default.aspx&fields=name,birthday,gender,email"
        scrolling="auto"
        frameborder="no"
        style="border:none"
        allowTransparency="true"
        width="100%"
        height="330">
    </iframe>

</div>
    </form>
</body>
</html>

Once data is received from FB in your site, you can insert it in your database to complete the registration. You can even add custom fields in the registration so that, FB registration will prompt user for that information so that you dont need your custom registration form at all.

Conclusion

By using Facebook registration plugin (and many other FB plugins), you can relieve visitors from tedious task of profile/user management. Please visit FB developer page for complete details.

-- Feedbackty/Comments are welcome :)