Simple .NET MVC 3 web application with integrated Facebook OAuth API

Introduction

Before creating a .NET MVC application, we have to register the domain name that will be used for the web site at the Facebook development site: http://developers.facebook.com/setup/. After successful registration, we will have a Facebook APIKey and Facebook Secret.

Now let’s create a simple ASP.NET MVC application in VS:

1_1.png

I will use the Facebook API button in this sample to show an alternative log in option to the user. Let’s change the_LogOnPartial.cshtml file in such a way:

 Collapse
@if(Request.IsAuthenticated) {
    <text>Welcome <strong>@User.Identity.Name</strong>!
    [ @Html.ActionLink("Log Off", "LogOff", "Account") ]</text>
}
else {
    <fb:login-button perms="email,user_checkins" onlogin="afterFacebookConnect();" 
       autologoutlink="false" ></fb:login-button>
    <div id="fb-root" style="display:inline; margin-left:20px;"></div>
    @:[ @Html.ActionLink("Log On", "LogOn", "Account") ]
}
<script language="javascript" type="text/javascript">
    window.fbAsyncInit = function () {
        FB.init({ appId: ' -- YOUR REAL APPLICATION ID SHOUD BE HERE --', 
                  status: true, cookie: false, xfbml: true });
    };
    function afterFacebookConnect() {
        FB.getLoginStatus(function (response) {
            if (response.session) {
                window.location = "../Account/FacebookLogin?token=" + 
                       response.session.access_token;
            } else {
                // user clicked Cancel
            }
        });
    };
    $(document).ready(function () {
        if (document.getElementById('fb-root') != undefined) {
            var e = document.createElement('script');
            e.type = 'text/javascript';
            e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
            e.async = true;
            document.getElementById('fb-root').appendChild(e);
        }
    });
</script>

The following elements were added to the control:

  • Facebook login button (fb:login-button).
  • Container which will contain all Facebook scripts (div id="fb-root").
  • FB initialization script (FB.fbAsyncInit). You have to replace the sample appId value with the real one received when registering your app on the Facebook development site.
  • afterFacebookConnect – script which will be called after the user closes the Facebook login dialog window (after successful or failed login).
  • Script for loading Facebook JavaScript libraries (e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';).

After successful login, we will have the access_token value, and now we can load detailed user’s info, store this info (if we need to), and authenticate the user. To do this, we will redirect the user to theAccount.FacebookLogin action and pass the access_token value as a parameter to this action. So at this stage, we will implement the “FacebookLogin” action. The created action will look like this:

 Collapse
using System.Web.Mvc;
using System.Web.Security;
using MVCOAuth.Models;
using System.Net;
using Newtonsoft.Json.Linq;
using System;

namespace MVCOAuth.Controllers
{
    public class AccountController : Controller
    {
        [HttpGet]
        public ActionResult FacebookLogin(string token)
        {
            WebClient client = new WebClient();
            string JsonResult = client.DownloadString(string.Concat(
                   "https://graph.facebook.com/me?access_token=", token));
            // Json.Net is really helpful if you have to deal
            // with Json from .Net http://json.codeplex.com/
            JObject jsonUserInfo = JObject.Parse(JsonResult);
            // you can get more user's info here. Please refer to:
            //     http://developers.facebook.com/docs/reference/api/user/
            string username = jsonUserInfo.Value<string>("username");
            string email = jsonUserInfo.Value<string>("email");
            string locale = jsonUserInfo.Value<string>("locale");
            int facebook_userID = jsonUserInfo.Value<int>("id");

            // store user's information here...
            FormsAuthentication.SetAuthCookie(username, true);
            return RedirectToAction("Index", "Home");
        }

And that’s it! We have integrated alternative Facebook authentication on the MVC site. Before login:

R_1.png

After successful Facebook authentication:

R_2.png

Hope this will be helpful for someone!

 

 

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s