Integrating Facebook in ASP Website using C# SDK

If you like it or hate it, you can’t get away with the fact that Facebook is present all over the web. Whether it’s a complex web application or just a news blog, every site uses Facebook for driving traffic. Integrating your web app or website with Facebook is easy and free. Apart from driving traffic to your site it also makes your web site more social and tailored for the users. You can access user’s data from Facebook to simplify or eliminate your own user registration process. If you have a asp.net website you can use Facebook C# SDK for integrating Facebook within your website/web application.

Creating a Facebook App
First of all we need to create an app through which the website will connect with users.

  1. Visit https://developers.facebook.com/apps and click on ‘Create New App’.
  2. Fill in the desired App Name and Namespace. Remember these must be unique.
  3. On the basic settings page look for ‘Select how your app integrates with Facebook’ section and choose ‘Website with Facebook Login’.
  4. In the Site URL field, enter your site address. I am working locally, so I added http://localhost:8779/ (Don’t forget to put a trailing ‘/’).

Note: Facebook keeps changing the developer interface. So, may be when you’re reading this post you have to go through a different set of steps while a creating a new app and configuring it.

Create a new Facebook App
Facebook App Settings


Installing Facebook C# SDK

Next step is to add Facebook C# SDK to your website. Search for ‘facebook‘ in the NuGet Package Manager. Install the latest stable release. In my case it was 6.1.4.

Facebok C# SDK NuGet

Note: Make sure you have a recent version of NuGet if not, download it from here.

Getting Started with code
I have created a simple interface with a button, two labels and a listbox.

Facebook ASP App Design
Design

 

User Authentication
On the click of the button, we allow users to connect with our app and grant the necessary permissions through Facebook’s OAuth dialog. For this we create a FacebookClient and through that a login URL. We have to add a few parameters in the login url:
app id,
a url to which users will be redirected,
response type,
and finally the permissions we require from the users.

 

This will take the user to Facebook Login page (if already not logged in) and then to our app login dialog. A user can accept or cancel the dialog, in both cases the user will be redirected back to our page.

Facebook OAuth Dialog
OAuth Dialog

Receiving Access Token
Our very next step is to receive an access token so that we can make requests to Facebook Graph API on behalf of the user. When the user is redirected back to our website, an auth code is appended in the URL. We have to exchange that code with an access_token.

 

First we extract the code from URL then we do a post request to Facebook and exchange the code for an access_token. Also, you can know the expire time for a user access token by querying response.expires which returns the number of seconds until the token expires.

Getting User Information
After getting the access token, our work is mostly simplified. Let us find user’s id,name and friend list. All these come under the basic info and we don’t need ask for a permission. As we asked for the permission to access email id of the user we can easily extract it along with name and id. So here’s the extended codind after the previous part.

 

 

Facebook C# SDK ASP .NET

OAuthException – #100
At this moment (i.e the code is still present in the url), if you reload the page you will experience an OAuthException – #100 “This authorization code has been used.“.
What’s happening is, we are again exchanging the code for an access token on the page load. Facebook could return us the already generated access token but it doesn’t. Rather it perceives a call to generate a new access token. You can track this Facebook bug here.
So what we could do and actually we should do is check if the user is already signed in i.e look for the session variable we stored when the user signed in. So, here’s a better a page_load method.

 

User Cancels Login Dialog
What if the user clicks on ‘Cancel’ rather than ‘Go To App’. The user will still be returned to our site but instead of code there would be 3 other parameters in the url namely error, error_reason, error_description. Taking this to account, here’s a modified page_load event.

 

Here’s the output received when the user clicks on ‘Cancel’: YOUR_REDIRECT_URI?error_reason=user_denied&error=access_denied&error_description=The+user+denied+your+request.

Logout
You may also want to allow the users to logout and hide all the social details. In this sample app, as you have noted earlier the text for Login Button changes to Log Out when the user logs in. So, through the button’s text we can know if the user wants to Log In or Out.

 

Avoiding OAuthException
An OAuthException may occur if you try to use a expired access token. Access token may expire in the following cases:
> The token expires after expires time (2 months is the default for server-side auhentication flow & 2 hours    for client-side auhentication flow.).
> The user changes his password.
> The user de-authorizes your app.
> The user logs out of Facebook.

So, you must surround the piece of code which makes the use of access token with a try catch block.

 

These were just sample examples on how to work with the sdk. It’s up to you, how you incorporate these pieces of code in a real world web application and make the most out of Facebook.

Let your friends know that you are developing a Facebook App by sharing this article 😛

UPDATE
Must read the second part, A Sample Facebook App using Facebook C Sharp SDK.

27 thoughts on “Integrating Facebook in ASP Website using C# SDK”

  1. Before some days, I tried to work with Facebook SDK but after a little bit work, I gave it up as I was really struck and could not find guidance. But now reading your tips, i feel that it was easy.

  2. This simple little tutorial really helped me, thanks! One correction though… GetLoginUrl should _not_ include the client_secret value. If this Url is being presented to a user to (which it should be, since they need to be taken to FB to authorize the access) then it'll expose the client secret to the user. GetLoginUrl just appends any value you send it to the query string, it's not smart enough to filter out something like the client secret. Reference: http://stackoverflow.com/q/15139516/328193

  3. Good catch with that. I blindly followed the developer's tutorial. Sorry for spreading some poor knowledge.
    The article is now updated. So you can trust the codes as always.

    It's not a little tutorial though 😛

  4. Hello,
    nice tutorial, one query :
    if user login on website using facebook and logout, so it should logout from website only not logout facebook.com? how could get it done.
    Pl suggest.

    thanks

  5. There is no way a user can logout from app only and doesn't even makes sense(you might be interested in reading more about OAuth protocol). So if you want to disconnect a user from your app only then don't call the fb.GetLogoutUrl, just delete the session values.

  6. If I login, I will see only my details, if my friend login he will see his.

    How can implement this.and get the details,name ,email,etc

  7. i am working on this app and included all files but getting namespace dynamic , jsonarray,facebookclient couldnot be found.I am working on vs 2008 and couldnot integrate nuget in my project kindly help me in removing these error

  8. If your app is completed and ready to be used by everyone, you need to disable the sandbox mode.
    To disable sandbox mode:
    1 Navigate to https://developers.facebook.com/apps
    2 Click on Edit App
    3 Navigate to Settings > Basic from the left sidebar.
    4 Set 'Sandbox Mode:' to 'Disabled'

    If your app is still in development and not ready for public use, you can restrict it's usability only to certain users like Testers and Developers. You can add users(developer/admins/testers) by visiting Settings > Developer Roles.

  9. how to ask for friends permission for accessing their details in asp.net website? as in facebook new rule in version 2.2; we have to get user request. thank you!

Leave a Reply to Anonymous Cancel Reply

Your email address will not be published. Required fields are marked *