ASP.NET - login with facebook and graph API

Social Media is growing by leaps and bounds now days. That is why more and more websites are trying to take advantage of this social buzz by integrating them in one way or other. 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. The advantage to users is they don't need separate login for your site and one of the social media site like Facebook. Benefit for your website is the large user base of facebook. Your website can easily convey a good referral message to user's connection once the user has registered to your website using facebook authentication.

In this article, we will look at a simple web application, that can help you visualize the addition of Login By facebook functionality to your asp.net web application.

Facebook Application ID

It is mandatory to create a Facebook application on their developer portal and get the ApplicationId from there, which we can use in our code to authenticate user against facebook graph API.

We will be using Facebook Graph JSON responses in our code, so in order to deserialize the JSON string we need to create few class as follow:

 

public class FacebookUser
{
    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 FacebookLocation location
    { get; set; }
}

public class FacebookLocation
{
    public string id
    { get; set; }

    public string name
    { get; set; }
}

 

When user authenticate against Facebook, facebook will send Access Token, which we can use on behalf of user to make further requests to Facebook. We need to pages here:

  1. Front end page with Login link, which allows user to open Facebook Login dialog
  2. A callback page to which we redirect autheticated user to get additional information about user from Facebook.

Here is code for default.aspx page:

 

<body>
    <div id="fb-root"></div>   
    <a href="#" onclick="loginByFacebook();">Login with Facebook</a>

    <%-- now this is some required facebook's JS, two things to pay attention to
	1. setting the ApplicationID, To make this project work you have to edit "callback.aspx.cs" and put your facebook-app-key there
    2. Adjust the permissions you want to get from user, set that in scope options below. --%>
    <script type="text/javascript">
        window.fbAsyncInit = function () {
            FB.init({ appId: '<%= FacebookLogin.callback.FaceBookAppKey %>',
                status: true, // check login status
                cookie: true, // enable cookies to allow the server to access the session
                xfbml: true, // parse XFBML
                oauth: true // 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_stream' });
        }

        function FacebookLoggedIn(response) {
            var loc = '/callback.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>
</body>

 

Code for callback.aspx

Here we are fetching user's additional details to display it (alternatively you can store it in your database). Please note the ApplicationID field here, which you need to replace with your own application Id.

 

public partial class callback : System.Web.UI.Page
{
	//TODO: paste your facebook-app key here!!
    public const string FaceBookAppKey = "XXXXXXXXXXXXX";

	protected void Page_Load(object sender, EventArgs e)
	{
        if (string.IsNullOrEmpty(Request.QueryString["access_token"])) return; //ERROR! No token returned from Facebook!!

		//let's send an http-request to facebook using the token			
        string json = GetFacebookUserJSON(Request.QueryString["access_token"]);

        //and Deserialize the JSON response
        JavaScriptSerializer js = new JavaScriptSerializer();
        FacebookUser oUser = js.Deserialize<FacebookUser>(json);

        if (oUser != null)
        {
            Response.Write("Welcome, " + oUser.name);
            Response.Write("<br />id, " + oUser.id);
            Response.Write("<br />email, " + oUser.email);
            Response.Write("<br />first_name, " + oUser.first_name);
            Response.Write("<br />last_name, " + oUser.last_name);
            Response.Write("<br />gender, " + oUser.gender);
            Response.Write("<br />link, " + oUser.link);
            Response.Write("<br />updated_time, " + oUser.updated_time);
            Response.Write("<br />birthday, " + oUser.birthday);
            Response.Write("<br />locale, " + oUser.locale);
            Response.Write("<br />picture, " + oUser.picture);
            if (oUser.location != null)
            {
                Response.Write("<br />locationid, " + oUser.location.id);
                Response.Write("<br />location_name, " + oUser.location.name);
            }
        }
	}

	/// <summary>
	/// sends http-request to Facebook and returns the response string
	/// </summary>
	private static string GetFacebookUserJSON(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 wc = new WebClient();
		Stream data = wc.OpenRead(url);
		StreamReader reader = new StreamReader(data);
		string s = reader.ReadToEnd();
		data.Close();
		reader.Close();

		return s;
	}
}

 

You can take a look at the Demo - SignIn with FaceBook in ASP.NET.

Comments (13) -

  • G Orychka

    G Orychka

    6/20/2012 12:29:37 AM | Reply

    Nice blog, thanks for the info.

  • Nagendra

    Nagendra

    6/29/2012 7:48:44 AM | Reply

    hi...
    i am using your code i didn't get email and birthday...
    what can i do...please help me..


    thank you

  • Nagendra

    Nagendra

    6/29/2012 7:52:12 AM | Reply

    and it shows the error The remote server returned an error: (400) Bad Request. at GetFacebookUserJSON string stream....please help me....

  • Admin

    Admin

    6/29/2012 9:46:41 PM | Reply

    Hi Narendra,

    To get the information about user, you'll first need to get permissions from the user to read those data from his profile.

    See here developers.facebook.com/.../ lists different permissions. You can set the required permissions in your facebook application setup page.

    Thanks

    • Nagendra

      Nagendra

      7/12/2012 3:06:11 AM | Reply

      hi.. thank you for your help. but this code works only client side not working in server side. in server side the page goes to error page. can i do any changes in app settings.. please help me..


      thank you....

    • Nani

      Nani

      8/16/2012 12:53:45 AM | Reply

      hi...
      how can i call manage_pages..
      i can entered it in scope. the pages are getting but i didn't understand how can i call it in front end..
      please help me

      thank u...

  • Nagendra

    Nagendra

    7/14/2012 4:08:28 AM | Reply

    hi...
    thank you very much..
    i used this code in my site..
    it's working....

  • shujaath

    shujaath

    7/24/2012 10:36:18 PM | Reply

    Nice it helped me a lot!

  • hari

    hari

    8/16/2012 12:50:40 AM | Reply

    hi..
    i want code for how to call manage_pages ..
    and how can i bind it in dropdownlist
    please help me..


    thank u....

    • Jagadeesh

      Jagadeesh

      8/17/2012 12:23:07 AM | Reply

      hi..
      i want c# code for how to import facebook pages  in dropdownlist.



      thank you...

  • Ram

    Ram

    10/16/2012 6:37:29 AM | Reply


    I got this error

    The name 'FacebookLogin' does not exist in the current context

    • Admin

      Admin

      10/20/2012 4:14:21 AM | Reply

      Just use your facebook application Id in place of <%= FacebookLogin.callback.FaceBookAppKey %>

  • Ram

    Ram

    10/16/2012 6:56:20 AM | Reply

    Hi

    I got this error  The name 'FacebookLogin' does not exist in the current context,please help me



Pingbacks and trackbacks (1)+

Loading