How to create a new Facebook application? How to authenticate Facebook users? How to retrive user's information? I had so many questions howering around my head when I started developing my first Facebook app. This article tries to answer some of them, and I hope it will save you some time if you intend to use Facebook API in your ASP.NET projects.
How to create a new Facebook app?
If you already know how to do this, please skip this step. If not, please visit the
Facebook developers site, and if you don't have one, create your Facebook developer account. I will assume that you have the permissions needed to create a new Facebook application. Click on the
apps link in the main menu and choose
Create New App button.
You will be prompted to provide a valid Facebook
app name and
namespace.
Facebook app basic settings
We will set only the basic application settings. Please add your app domain and URL. Facebook will accept your local test domains, and they will come really handy during the development phase. You will later need your App ID and App Secret Key which are provided here.
How to authenticate a Facebook user?
JavaScript SDK
Register the channel file address inside the <head> tag. The channel file addresses some issues with cross domain communication in certain browsers. The contents of the channel.html file can be just a single line:
<script src="http://connect.facebook.net/en_US/all.js"></script>
Tip: If you want to localize dialogs replace en_US with the desired county code.
The following code will load and initialize the JavaScript SDK with all standard options. Replace
YOUR_APP_ID with the appropriate Facebook app key.
The best place to put this code is right after the opening
<body> tag. To register it from your codebehind, please use the following code:
if (!Page.ClientScript.IsClientScriptBlockRegistered("facebook_api"))
if (!Page.ClientScript.IsStartupScriptRegistered("facebook_api_init"))
Page.ClientScript.RegisterStartupScript(typeof(string), "facebook_api_init",String.Format("FB.init({{appId: '{0}', status: true, cookie: true, xfbml: true, oauth: true }});", "YOUR_APP_ID"), true);
The JavaScript SDK requires the fb-root element in order to load properly and a call to FB.init to initialize the SDK with your app ID correctly. It is very important to add the following line, preferably after the opening FORM tag on your page.
Authentication and Authorization
FB.login
The easiest way to authenticate users is to call FB.login which prompts the user to authenticate your application using the OAuth Dialog. Calling FB.login results in the JS SDK attempting to open a popup
window. As such, this method should only be called after a user click
event, otherwise the popup window will be blocked by most browsers.
FB.login(function(response) {
// handle the response
}, {scope: 'email'});
Permissions
By default, calling FB.login will attempt to authenticate the user with only the basic permissions. If you want one or more
additional permissions, call FB.login with an option object, and set the scope parameter with a comma-separated list of the permissions you wish to request from the user.
Putting it all together
After you sucessfully authenticated your users, it is time to integrate your ASP.NET application with Facebook. In my opinion, the the best way to do it is to use the standard
Facebook c# sdk. Download the latest version and add the following references to your project: Facebook.dll and Facebook.Web.dll. Modify the configSections of your web.config by adding the following line:
<section type="Facebook.FacebookConfigurationSection, Facebook" name="facebookSettings" allowLocation="true" allowDefinition="Everywhere" />
Add the new
facebookSettings just after the configSections tag and provide Facebook app Id and secret key.
<facebookSettings
appId=""
appSecret="" />
Our goal is to authenticate the user and fetch some of his/her information. I am usually adding the boilerplate code to the master page. Take a look at following markup.
Tip: Don't forget to add the div tag with the id fb-root .
<head runat="server">
<title></title>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div id="fb-root"></div>
<div>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
Now let's take a look at the master's page code behind. We have registired two additional scripts for user authentication (
facebook_login and
facebook_logout). In the Facebook login script we are prompting user to grant access to our Facebook app.
In our case, we are asking user to allow access to his basic information, email and a date of birth. If user grants access to our application, we are raising the postback with the eventArgument
"FacebookLogin" .
Note: Please replace YOUR_APP_ID with the appropriate facebook app key
public partial class DefaultFacebook : System.Web.UI.MasterPage
{
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (!Page.ClientScript.IsClientScriptBlockRegistered("facebook_api"))
if (!Page.ClientScript.IsStartupScriptRegistered("facebook_api_init"))
Page.ClientScript.RegisterStartupScript(typeof(string), "facebook_api_init",
String.Format("FB.init({{appId: '{0}', status: true, cookie: true, xfbml: true, oauth: true }});", "YOUR_APP_ID"), true);
if (!Page.ClientScript.IsStartupScriptRegistered("facebook_login"))
{
string facebookLogin = String.Format("function fblogin() {{ FB.login(function(response) {{ if (response.authResponse) {{ {0} }} else {{ {1} }}}}, {{ scope: '{2}' }});}}", this.Page.ClientScript.GetPostBackEventReference(this.Page, "FacebookLogin", false), this.Page.ClientScript.GetPostBackEventReference(this.Page, "FacebookLogout", false), "publish_stream,email,user_birthday");
Page.ClientScript.RegisterStartupScript(typeof(string), "facebook_login",
facebookLogin, true);
}
if (!Page.ClientScript.IsStartupScriptRegistered("facebook_logout"))
{
string facebookLogout = String.Format("function fblogout() {{ FB.logout(function(response) {{ {0} }}); }}", this.Page.ClientScript.GetPostBackEventReference(this.Page, "FacebookLogout", false));
Page.ClientScript.RegisterStartupScript(typeof(string), "facebook_logout",
facebookLogout, true);
}
}
}
Now let's create a page where we will actually authenticate our users. We have added a
Facebook Log In link and called
fblogin function in its onclick event handler. We have also added the literal control
ltlFacebookUserInfo which will be used to show the user inofrmation.
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<a href="#" class="facebook-login" onclick="fblogin();return false;">
Facebook Log In
</a>
<br />
<asp:Literal ID="ltlFacebookUserInfo" runat="server">
</asp:Literal>
</asp:Content>
To raise the postback on the page we have implemented the
IPostBackEventHandler interface. In its
RaisePostBackEvent handler we are checking the value of the
eventArgument parameter. If its value equals
FacebookLogin, we can be sure that a current user approved our application.
We created a new instance of the FacebookApp class to check if the user is really connected. User information is provided via the Open Graph standard (facebookApi("me")). The result that we will receive will be packaged inside the JsonObject.
public partial class FacebookAuthentication : System.Web.UI.Page, IPostBackEventHandler
{
#region IPostBackEventHandler Members
public void RaisePostBackEvent(string eventArgument)
{
if(eventArgument == "FacebookLogin")
{
StringBuilder sb = new StringBuilder();
Facebook.FacebookApp facebookApp = new Facebook.FacebookApp();
if (facebookApp.Session != null)
{
var facebookUser = facebookApp.Api("me") as JsonObject;
if (facebookUser.ContainsKey("name") && facebookUser["name"] != null)
sb.AppendFormat("<strong>You are logged in as:</strong> {0}</br>", facebookUser["name"].ToString());
if (facebookUser.ContainsKey("gender") && facebookUser["gender"] != null)
sb.AppendFormat("Gender: {0}</br>", facebookUser["gender"].ToString());
if (facebookUser.ContainsKey("username") && facebookUser["username"] != null)
sb.AppendFormat("Username: {0}</br>", facebookUser["username"].ToString());
if (facebookUser.ContainsKey("email") && facebookUser["email"] != null)
sb.AppendFormat("E-mail: {0}</br>", facebookUser["email"].ToString());
}
ltlFacebookUserInfo.Text = sb.ToString();
}
else if(eventArgument == "FacebookLogout")
{
//implement logic for logout
}
}
#endregion
}
What have we learned?
In this article we have learned how to authenticate Facebook users and get user information using the Open Graph protocol. You can now fetch additional information about your users, including complete "user graphs" and all other information for which you get their permission.