Login & logout using facebook account using Facebook C# SDK and asp.net mvc3

In this tutorial I will show you that how can we do login & logout using facebook Id from your website.

Step 1:
First you need to create empty mvc3 application & Install Facebook C# SDK using nugget package (see the detailed information about installing Nuget package http://csharpsdk.org/docs/web/getting-started)

Step 2:
Before you even begin using the Facebook C# SDK you must create a Facebook application. To do so navigate to http://developers.facebook.com/apps and click the ‘Create New App’ button. Follow the steps to create an app and record your AppId for use later.

Step 3:
Now create following things
1. Views : Index.cshtml & Info.cshtml ( _Layout.cshtml should be masterpage both views)
2. Controllers : AccountController.cs & HomeController.cs
3. Model : InfoModel.cs
As show in bellow snapshot.

Step 4:
Web.Config Settings

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

In appSettings of your web.config add these two keys of your application.

Step 5:
Index.cshtml

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Index</h2>
@Html.BeginForm("Loginfb","Account")
    {
           <input type="submit" value="Login Using Facebook" id="saveButton"/>
    }

Here we are creating one submit button which on click will call LoginFb action from AccountController.

Info.cshtml

@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"/>
    }    
}

Here we are showing information of user who has logged in using facebook account & also logout button which on click will call LogOut action of AccountController.

Step 6:
InfoModel.cs

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

Here I have initialised properties , using which I will show data in Info.cshtml Page.

Step 7:
HomeController.cs

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

In home controller I am getting app Id & Secret Key from web.config.
Here I have created two actions
1. Index – this will call Index.cshtml
2. Info – This action is called from Loginfb Action of AccountController, Here I am getting information of user & assigning it to InfoModel & sending this to Info.cshrml view.

AccountController.cs

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

        }
    }

Here I have created two actions
1. Loginfb – This action redirects to the facebook login page after authenticating the facebook appId . If user is successfully logged in then it is redirected to Info Action of HomeController(This is given as redirectUri ).
2. LogOut – Here I am passing access token of user & url (Here I have passed “http://localhost:8691”) of the page in “next” parameter which has to be shown after user is logged out.

That’s all , now you can login & logout using facebook account from your website

admin

  • Alexandra

    Hi,
    thank you so much. This is the first valuable tutorial I’ve found so far.

  • Isuru Alahakoon

    Hi Vaibhav,
    Thank u very much ur valuable post. Its working without any issue. But I want to get user profile image too. How can I do that ?
    Thanks…!

    • Vaibhav Shah

      Hi,
      You can not get profile picture directly. But there is way to get profile picture.
      First add bellow property into InfoModel
      public Facebook.JsonObject picture { get; set; }

      Then do some small changes in actionResult Info()

      // Get the user’s profile information
      dynamic me = client.Get(“/me”,
      new
      {
      fields = “first_name,last_name,email,picture”,
      access_token = accessToken
      });

      var userInfo = new InfoModel()
      {
      firstName = me.first_name,
      lastName = me.last_name,
      emailId = me.email,
      picture = me.picture,
      accessToken = result.access_token
      };

      By doing this you will get JasonObject in picture which contains url of profile image.
      You can use that to get profile picture.

  • http://www.jogrunrace.com/ JogRunRace

    Thanks for the tutorial. It saved me a lot of work.

  • Suresh BaBu

    please mail me suresh_babu9@outlook.com

  • Suresh BaBu

    Thanks For valuable post, i want post a status with my app. please help this …
    thanking you advance..