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 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:


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

        function loginByFacebook() {
            FB.login(function (response) {
                if (response.authResponse) {
                } 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;
                window.location = loc + '?authprv=facebook&access_token=' + response.authResponse.accessToken;


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, " +;
            Response.Write("<br />id, " +;
            Response.Write("<br />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, " +;
            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, " +;
                Response.Write("<br />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("{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();

		return s;

Comments (13) -

  • G Orychka
    Nice blog, thanks for the info.
  • Nagendra
    i am using your code i didn't get email and birthday...
    what can i do...please help me..

    thank you
  • Nagendra
    and it shows the error The remote server returned an error: (400) Bad Request. at GetFacebookUserJSON string stream....please help me....
  • Admin
    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 lists different permissions. You can set the required permissions in your facebook application setup page.

    • Nagendra
      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
      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
    thank you very much..
    i used this code in my site..
    it's working....
  • shujaath
    Nice it helped me a lot!
  • hari
    i want code for how to call manage_pages ..
    and how can i bind it in dropdownlist
    please help me..

    thank u....
    • Jagadeesh
      i want c# code for how to import facebook pages  in dropdownlist.

      thank you...
  • Ram

    I got this error

    The name 'FacebookLogin' does not exist in the current context
    • Admin
      Just use your facebook application Id in place of <%= FacebookLogin.callback.FaceBookAppKey %>
  • Raphael
    Thank your very much. Very useful content. Worked great on my site.
Comments are closed