Facebook Login Integration

Categories C#, Facebook, MVC
Tags , , ,

This past week I was tasked with integrating Facebook Login with a new MVC3 site I am working on and the whole process is made remarkably easy with the help of a few NuGet packages.

Now I was following along with the documentation that can be found on Codeplex here but I have to confess I did get a little confused with it (maybe it was me being blonde) as it didn’t appear to give me the complete picture so I figured it was worth my while documenting my findings in the hope of saving someone else a little time, or myself in the future.

Read on below the break for all the details.

So let’s assume you have your existing MVC3 application and you have a standard login system using FormsAuthentication (login and password) and you want to add the “Login with Facebook” button like below:

image

The first thing you are going to want to do is get the Facebook SDK packages shown below from NuGet.

image

This will make a few changes to to your project. To start with it will add references to the following assemblies:

  • Facebook
  • Facebook.Web
  • Facebook.Web.Mvc

It will also add a new partial view to your Shared views folder called FacebookInit.cshtml and your going to need to add this to your Views where you want to include Facebook functionality.

Now in my case I have added it to the _Layout.cshtml shared view, so it will be available site wide, just after the call to RenderBody like so.

@RenderBody()
@{ Html.RenderPartial("FacebookInit"); }

One other change is a new section will be added to your web.config which will contain the Facebook settings for your application.

<facebookSettings appId="{app id}" appSecret="{app secret}" />

Your going to need a Facebook developer account for this and once you have one you can create your application over here http://www.facebook.com/developers/createapp.php.

Setting up your application is easy, just follow the steps shown below:

1. Click on the Create New App button at the top right image

2. Give you app a name

image

3. Answer the security check question.

image

4. Select the Website option shown below and provide the URL for your site. For testing purposes you can use localhost or whatever url you are using to host your web site during developmentimage

5. Note the App ID and App Secret and insert those in the Facebook Settings found in your web.config discussed above.

OK so now that we have that out of the way let’s get in to integrating with your login system.

Adding the Facebook button is easy, just add the element below:

<fb:login-button perms="email,user_birthday,user_hometown">Login with Facebook</fb:login-button>

That ‘perms’ attribute is important as it will dictate what permissions you will be requesting from the Facebook user that is logging in to your account and ultimately what data you can collect about the user. Asking for to much might put your users off so give some thought to what information you really need about the user.

You can get a full list of what’s available here http://developers.facebook.com/docs/reference/api/user/. The Permissions column shows you the perm attribute you will need to add to request the data.

So with the permissions above the following dialog will be displayed requesting permissions when the Login with Facebook button is clicked.

image

So with that out of the way we now need to complete the login process from within our application.

If you create a default ASP.NET MVC3 Web Application you will get an account controller out of the box which will use the default asp.net MembershipProvider and this will provide a LogOn View.

If we just place the markup for the FB button on the page as is we can hook in to the default LogOn action as shown:

public ActionResult LogOn()
{
    if (FacebookWebContext.Current.IsAuthenticated())
    {
        FacebookIntegration fb = new FacebookIntegration();
        fb.RegisterOrUpdateFacebookUser();
        return RedirectToAction("Payment", "Checkout");
    }
    return View("LogOn");
}

After you click on the Login with Facebook button and Allow the application it will return to this controller and from here we can use the FacebookWebContext to determine if the user is Authenticated. You will need to add the following using statement:

using Facebook.Web;

The FacebookIntegration class is some custom code I use to then register the user internally and store the information requested about the user. If the user is new to our site then it will create a new account internally and use the Facebook User ID as the key field. If the user is a returning user then it will just update the existing account to make sure we have all the latest information about our clients.

 

In my case I am using a custom Membership and Role Provider implementation that uses EF Code First.  How you choose to store the accounts is entirely up to you but let me show you the code to get the information from Facebook.

using Facebook.Web;

 

public void RegisterOrUpdateFacebookUser() { try { // Get the Facebook User Details var fb = new FacebookWebClient(); dynamic result = fb.Get("me"); string userId = result.id.ToString(); // Parse the users birthday CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US"); DateTimeStyles styles = DateTimeStyles.None; DateTime birthday; if (!DateTime.TryParse(result.birthday, culture, styles, out birthday)) { birthday = DateTime.Parse("Jan 01 1900"); } using (MyContext db = new MyContext()) { // Check if the Facebook User is already a member User user = (from u in db.Users where u.UserId == userId select u).SingleOrDefault(); // If not then we need to create an account if (user == null) { MyMembershipProvider membershipProvider = new MyMembershipProvider(); MyRoleProvider roleProvider = new MyRoleProvider(); Role clientRole = roleProvider.GetRoleByRoleName("Clients"); MembershipCreateStatus createResult = membershipProvider.CreateUserFromFacebook( userId , result.username , result.first_name , result.last_name , result.email , birthday , result.gender , result.hometown.name , clientRole); Logging.LogInformation("Registered new Facebook User"); } else {

// Otherwise update the account user.Logon = result.username; user.FirstName = result.first_name; user.LastName = result.last_name; user.Email = result.email; user.Birthday = birthday; user.Gender = result.gender; user.Hometown = result.hometown.name; db.SaveChanges(); Logging.LogInformation("Updated details for Facebook User"); } } } catch (Exception e) { Logging.LogError(e); } }

The key thing to take away from above is how to actually read the information from FacebookWebClient as follows:

dynamic result = fb.Get("me");

Passing in “me” to the Get method will get the details for the currently Authenticated Facebook User and we store that in a dynamic variable.

From there we can just pull out the various pieces of information we need like so as properties of the dynamic variable.

result.email
 , result.gender
 , result.hometown.name

It’s worth noting that the Birthday is returned in US date format hence the code to parse the Date:

// Parse the users birtday
CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US");
DateTimeStyles styles = DateTimeStyles.None;
DateTime birthday;
if (!DateTime.TryParse(result.birthday, culture, styles, out birthday))
{
    birthday = DateTime.Parse("Jan 01 1900");
}

Well that’s pretty much it. Hopefully that has tied together a few of the loose ends that other articles on the subject missed and will save you (and me) some time in the future.

BondiGeek

3 thoughts on “Facebook Login Integration

  1. Rúbia Gardini on

    THANK YOU so much for your tutorial, I feel so pitiful that the most used Facebook SDK for C# is so messy in documentation.

  2. prdscsor on

    Thanks for valuable article, I am please if you provide source code or example for experiment.