How to Login via Facebook in ASP.NET

Aug 10, 10 How to Login via Facebook in ASP.NET

Recently I have encountered some nasty problems trying to build a Facebook login system. That’s why I am going to explain a full tutorial about every aspect you need to know about it.

1. Register your application

Go to http://developers.facebook.com/setup/ and enter the site name(it could be any) and the site URL(if you’re testing locally, type “http://localhost/”). With that set-up click on “Create application”.

facebook-create-application-id

Immediately, you will be presented your application’s settings. What you need is the “App ID”. In this case is “125512450828469″.

2. The HTML

2.1. Facebook Namespace

Add the following namespace to the html -> xmlns:fb=”http://www.facebook.com/2008/fbml” xml:lang=”en”
So the html tag should look like this: <html xmlns=”http://www.w3.org/1999/xhtml” xmlns:fb=”http://www.facebook.com/2008/fbml” xml:lang=”en”>

2.2. Facebook Scripts

At the end of the document add the following scripts:

<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
    FB.init({ appId: 'your App ID', status: true, cookie: true, xfbml: true });
    FB.Event.subscribe('auth.sessionChange', function (response) {
        if (response.session) {
            // A user has logged in, and a new cookie has been saved
        } else {
            // The user has logged out, and the cookie has been cleared
        }
    });
</script>

Insert your Id into the “appId” property.

2.3. Facebook login button

The last step of the HTML is to add the Facebook login button. You can place the button wherever you want. It has the following form:

<fb:login-button>Your button text here</fb:login-button>

You can type anything you want to appear on the button between the tags. In order to get the e-mail of the user you are trying to log in, set the perms attribute to “email”. So here’s the correct version:

<fb:login-button perms=”email”>Login via Facebook!</fb:login-button>

3. The code and how it works

private string FacebookLogin()
{
    string appId = "your App ID";
    string cookieValue, accessToken, uid, url, userInformation, email = null;
    Regex getValues;
    Match infoMatch;
    MatchCollection valuesCollection;
    WebClient client;

    try
    {
            // Get the cookie
        cookieValue = Request.Cookies["fbs_" + appId].Value;

            // Get the values
        getValues = new Regex(@"(?<==)[^&]+");
        valuesCollection = getValues.Matches(cookieValue);

            /* The access_token and uid parameters are the first,
respectively last, in the cookie */
        accessToken = valuesCollection[0].ToString();
        uid = valuesCollection[5].ToString().Replace(@"""", "");

            // Build the URL and download it
        url = "https://graph.facebook.com/" + uid +
               "?access_token=" + accessToken;
        client = new WebClient();
        userInformation = client.DownloadString(url);

            // Get the email address
         getValues = new Regex("(?<=\"email\":\")(.+?)(?=\")");
         infoMatch = getValues.Match(userInformation);
         email = infoMatch.Value;
    }
    catch (Exception) { }

    return email;
}

Replace the appId with yours. Go ahead and login with a valid Facebook account.
Now, the cookie “fbs_” + appId holds the required information.
This is how it looks in my case:

“access_token=125512450828469%7C2.qi_hzJprQ7qGp7NJfFQwLw__.3600.1281441600-
100000714527321%7CXqRVpjBgLyZ0MQ4r7_GZmY4CpOw.&expires=1281441600&secret=T2bCRUnZrziKQxGAFAkQTg__&session_key=2.qi_hzJprQ7qGp7NJfFQwLw__.3600.1281441600-100000714527321&sig=0cd8f3dd46fc23d9f1e66b57a9debea6&uid=100000714527321″

We basically need 2 values: the access token and the uid, because this is how you access the user’s information in Facebook’s Graph:
“https://graph.facebook.com/” + uid + “?access_token=” + access token;

In order to get them, I firstly used a pretty Regex ((?<==)[^&]+) to extract all of them.

login-via-facebook-cookie-regex

After you have the whole values, get the access token (the first value in the collection) and the uid (the last value in the collection) individually.
Now that you have them, build the URL after the model above. If you’re curious to access the URL, you’ll see the data returned as JSON, that is organized as: “parameter”: “value”.
Using the last Regex, (?<=\”email\”:\”)(.+?)(?=\”) you get the exact e-mail value that you needed to operate on. Now it’s up to you to decide what your application does with the user’s Facebook e-mail. You can check if the e-mail is registered in your database and login the user, or redirect him to the registration page.

Hope you enjoyed the tutorial. Stay tuned for more.

Related posts:

  1. Using Regex to extract content between HTML tags

16 Comments

  1. Aliniuz /

    Useful article you got here my friend. Good job!

  2. Derek Prosise /

    good!it’s very useful!thx!

  3. Thanks very much Aliniuz and Derek!

  4. what happens if the user has not made his email public?

  5. The e-mail might not be made public on his Facebook profile, but when he uses the log-in system he specifically grants you access to his e-mail address. In fact, this is how it works, because from the JSON file you can extract the e-mail address only after the user has agreed to allow the application (your login system) to access his e-mail address.

  6. You’ve wrote a very excellent story.
    If it’s ok with you, I would like to seek permission to use your article as it relates to my obstruction. I will be happy to negotiate to pay you or hire you for this.

    With Regards from
    Republic Polytechnic

  7. Thanks! There’s no problem. You may use it as you wish.

  8. Useful article you got here my friend. Good job!

  9. Thanks for the article! Couple questions though:

    Where do you specify callback URL?
    And which page do you write FacebookLogin() function?

  10. Thanks for the article. The most informative I could find so far. But I have an issue.
    When I’m trying to read a cookie from server-side, it can’t find one. I get error: “Object reference not set to an instance
    of an object”. Any suggestions?

  11. Well, I’ve figured out some previous problems. But I’ve faced new one. It seems that my app can’t get userInformation.
    This variable contains an error below:

    {“error”:{“type”:”OAuthException”,”message”:”(#803) Some of the aliases you requested do not exist: fb5d010f9d890577a3fcd3a0…….”}}

    I cut the rest of ID for security reasons…
    Any ideas for the cause of the error?

    Thanks.

  12. Hmmm. I’ve Googled your error a little and if I’m not wrong Facebook changed the system a bit. Will research the problem and see if I find something useful. Meanwhile, give it a search and see if you too come across some useful information. Thanks very much for the previous appreciations.

  13. can we pass username and password through database and then get logged in..? i mean without using fb button.

  14. Jerome /

    I have followed your tutorial and it’s easy to implement but how do i link the c# facebook login method to the facebook login button or javascript which handles the login? I’m stuck at the last part getting access token. thanks

  15. Hi all! Sorry for the late reply, the website experienced some problems. Please check Facebook’s latest guidelines for integration.

    It’s been over a year and I didn’t keep up with anything Facebook might have changed with regards to this topic.

    What I wrote here a year ago it’s all that was needed to get it working; with everything as it is here.

    Thanks for reading the article!

Trackbacks/Pingbacks

  1. Autentificare via Facebook in ASP.NET | WorldIT - [...] editorului : Articolul a fost publicat initial in limba engleza pe Area72 si tradus de autorul acestuia. Recent am ...

Leave a Reply