Saturday, 13 February 2016

Login with facebook and graph API using Asp.net

Live Demo

Overview
Web is getting more and more occupied by Social Media  now days so, most of the websites are trying to take advantage  of this social buzz by integrating them in multiple ways. Obviously ,It saves great time for the end user too like , rather than creating account/Registering in websites to access resources which is very time consuming and boring  ,they just login with single click.Facebook has turned out to be the holders of user information that can be used to be the secure gateway/login into your web applications. Best part of it is your website can easily have huge user base with time by using Facebook authentication.
In this article, we will look at a simple web application, that can help you how to implement Login By Facebook functionality using asp.net web application.
Well, before implementation It is important to make  Facebook aware about our application. I mean to get Registered inside Facebook.

How To Register your Application in Facebook

To Register your application in Facebook you need to fallow below steps
go to https://developers.facebook.com

:-







Great you have registered your application,i mean Facebook knows your application now and will recognize requests from your application

HOW IT WORKS:

When user clicks on Sign in with Facebook button,i mean when user authenticate against Facebook, Facebook in return with send Access Token, which we can use on behalf of user to make further requests to Facebook.

SET UP ASP.NET WEB APPLICATION

We need to pages here:

  1. User UI  Login.aspx with Login link/button, which allows user to click and open Facebook Login dialog
  2. A FacebookLogin.aspx.cs page[code behind] to which we redirect authenticated user to get additional information about user from Facebook.It acts as callback page
  3. A class which will hold Facebook user details
  4. Web Config which will hold client id and other required details 

FacebookLogin.aspx

<%@ Page Language="C#" AutoEventWireup="true" 
CodeBehind="FacebookLogin.aspx.cs"
 Inherits="Faith.Web.Presentation.FacebookLogin" %>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Facebook Login</title>
 <script>
         //THIS IS CODE WHICH WAS CREATED WHILE REGISTERING OUR APPLICATION IN FACEBOOK CONSOLE
         //JUST COPY AND PASTE THAT SCRIPT
       window.fbAsyncInit = function () {
          FB.init({
              appId: '***************',
              status: true, // check login status
              cookie: true, // enable cookies to allow the server to access the session
              xfbml: true, // parse XFBML
              oauth: true,
              version: 'v2.5'// enable OAuth 2.0
          });
      };
      (function () {
          var e = document.createElement('script'); e.async = true;
          e.src = document.location.protocol +
          '//connect.facebook.net/en_US/all.js';
          document.getElementById('fb-root').appendChild(e);
      }());

      function loginByFacebook() {
          FB.login(function (response) {
              if (response.authResponse) {
                  FacebookLoggedIn(response);
              } else {
                  console.log('User cancelled login or did not fully authorize.');
              }
          }, { scope: 'user_birthday,user_about_me,user_hometown,user_location,email,publish_actions' });
      }

      function FacebookLoggedIn(response) {
          var loc = 'Facebooklogin.aspx';
          if (loc.indexOf('?') > -1)
              window.location = loc + '&authprv=facebook&access_token=' + response.authResponse.accessToken;
          else
              window.location = loc + '?authprv=facebook&access_token=' + response.authResponse.accessToken;
      }

    </script>
</head>
<body>
    <form id="form1" runat="server">
   <div>
     <a href="javascript:void(0)" onclick="facebookLogin();">
<img alt="Login with Facebook" src="img/btn-signin-facebook.png" style="border: none;" /></a>

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


FbUser

  public class FbUser
    {
        public long id
        { get; set; }

        public string email
        { get; set; }

        public string name
        { get; set; }

        public string first_name
        { get; set; }

        public string last_name
        { get; set; }

        public string gender
        { get; set; }

        public string link
        { get; set; }

        public DateTime updated_time
        { get; set; }

        public DateTime birthday
        { get; set; }

        public string locale
        { get; set; }

        public string picture
        { get; set; }

        public FbLocation location
        { get; set; }
    }
    public class FbLocation
    {
        public string id
        { get; set; }

        public string name
        { get; set; }
    }

FacebookLogin.aspx.cs

As we passed the access token from the FacebookLogin.aspx in querystring, we can use that here to make an API call to Google+ userinfo/email method to retrieve the user's email address. Using JavaScriptSerializer class we can deserialize the json string into the .net classes we created in first step.

 public partial class FacebookLogin : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["access_token"] != null)
            {
                if (string.IsNullOrEmpty(Request.QueryString["access_token"]))
                {
                    //   return; //ERROR! No token returned from Facebook!!
                    Response.Redirect("~/FacebookLogin.aspx");
                }
                //let's send an http-request to facebook using the token            
                string json = GetFbUserJSON(Request.QueryString["access_token"]);
                //and Deserialize the JSON response
                JavaScriptSerializer js = new JavaScriptSerializer();
                FbUser oUser = js.Deserialize<Fbuser>(json);
                //Here i take oUser Object properties value like email,userid and save them in session object
                //OTHER WAY YOU CAN SAVE THESE VALUES IN DATABASE
                HttpContext.Current.Session["Username"] = oUser.email.ToString();
                HttpContext.Current.Session["UserId"] = oUser.id.ToString();   
                //redirect user to authenticated homepage here now
                HttpContext.Current.Response.Redirect("Account/");   
            }
        }
        /// 
        /// sends http-request to Facebook and returns the response string
        /// 
        private static string GetFbUserJSON(string access_token)
        {
            string url = string.Format("https://graph.facebook.com/me?access_token={0}&
                        fields=email,name,first_name,last_name,link", access_token);
            WebClient webClient = new WebClient();
            Stream data = webClient .OpenRead(url);
            StreamReader reader = new StreamReader(data);
            string str = reader.ReadToEnd();
            data.Close();
            reader.Close();
            return  str ;
        } 
    }
 

Here is screen shot which shows JSON oUser after deserialize,you can fetch all object properties and save in database


Hope this helps Shabir

How to Build a Full-Stack Web App with Blazor

  Blazor Stack Overview Important Points: Blazor stack gives you options to create Web Applications without writing JavaScript (doesn't ...