Cutting Edge

Essential Facebook Programming: Authentication and Updates

Dino Esposito

Download the Code Sample

Dino EspositoFacebook is a rich and complex software platform, which exposes a sophisticated and multifaceted development framework to devel­opers. At first, the meaning of “Facebook programming” might not be clear. There are essentially two types of apps related to Facebook. One type comprises apps that live and thrive within the Facebook environment. These apps are essentially rich Web pages loaded in Facebook canvas pages and hosted in the main site. To use the app, users need to navigate to the Facebook site and log in to their own account. These apps can implement their own logic—­whatever you can express from within a Web page using JavaScript or other Web programming technologies—and can gain access to Facebook goodies such as friends, news feeds, media and more. To get started on this form of programming, just go to the “Apps on” page at

Another approach to Facebook programming involves integrating some core Facebook functionalities into existing apps, such as Web sites, mobile apps (for example, Android, iOS or Windows Phone) or desktop applications.

In this article I’ll focus on this aspect of Facebook programming and discuss how to use the Facebook C# API to authenticate users and post programmatically on behalf of the currently logged-in user.

Embedding the Like Button

When it comes to popular social networks such as Facebook and Twitter, the first level of integration with external apps is through the use of ad hoc buttons to “like” the page or tweet about it. Hardly any programming is required; it’s purely a matter of inserting some ad hoc markup into the Web pages.

So the simplest way to make your Web site more popular is to embed the Facebook Like button in a new iframe so that any user visiting the page can immediately like it on Facebook. Here’s the minimal markup you need:

<iframe src="">

You replace XXX with the URL of the page to like. In addition, you might want to add a bit of CSS style to the iframe element to make it better merge with the rest of the page. Figure 1 shows the final result.

The Facebook Like Button
Figure 1 The Facebook Like Button

The Like button is the simplest (and most popular) of the Facebook social plug-ins. Most of the time, you can integrate plug-ins in your Web pages via frames or ad hoc markup. Some plug-ins require the Facebook JavaScript SDK, and some only work if you have custom Facebook pages. I’ll discuss scripting Facebook in a future column.

Beyond using social plug-ins, integrating Facebook in apps (and not just Web sites) means being able to perform two main tasks: let users authenticate themselves with your app using their Facebook account, and enable the app to post to the Facebook walls of particular users. Let’s start with user authentication.

OAuth and the Old Dream of a Single Authentication Module

User authentication is a core function of just about any significant Web site. A decade ago, one of the best-selling points of ASP.NET in comparison to classic ASP was the availability of a highly reusable membership system that facilitated the development of an authentication layer in a fraction of the time normally required.

These days, however, having a custom authentication layer is an enticing option. By implementing an ad hoc authentication layer, developers make themselves responsible for safely storing passwords and for the costs of managing thousands of accounts or more. For users, that means yet another username/password pair to remember.

Years ago, the Microsoft Passport initiative was a smart but probably too-early attempt to make users’ lives easier when they moved across a few related sites. The idea behind Passport was that users just needed a single successful logon to freely navigate through all of the associated sites.

Bundled with older versions of ASP.NET, the Passport API is now officially gone. The problem it was devised to solve, however, is still present.

Today, OpenID ( is a great option for Web sites that need to authenticate their users but don’t want to charge them with yet another set of credentials. OpenID is a single sign-on (SSO) protocol that your site uses to connect to a third-party service provider that will manage the authentication for you. An OpenID-enabled site manages only the beginning and end of the authentication task. It redirects the user to the configured OpenID provider and gets identity information back when everything has happened.

While OpenID is a popular buzzword, another one is being discussed even more: OAuth ( What’s the difference?

 OpenID is exclusively an SSO protocol. An OpenID provider only manages the identities of registered users. But social networks such as Twitter and Facebook need more. One app might simply want to let users authenticate via Facebook. Another might want to authenticate via Facebook but also post to the user’s wall. Yet another app might want to read the user’s timeline and recent activity. On top of everything, there’s authentication (which can be managed via the OpenID protocol), but the same user may grant different permissions to different apps. And this is an aspect that OpenID was not designed to handle.

OAuth is the protocol that Twitter and Facebook use to handle authentication and authorization. An OAuth provider doesn’t simply return identity information. It asks the user which permissions he wants to grant to the app and then packages everything, credentials and permissions, into an access token. The client app will then pass the access token to perform any permitted operation on behalf of the user. One benefit of OAuth (and OpenID, as well) is that the provider never discloses user credentials to the app. In addition, when OAuth is used, the end user can revoke permissions to any app at any time. So, for example, imagine that at some point you authenticate with app XYZ using Twitter (or Facebook) and grant XYZ permission to post on your behalf. You can revoke this permission at any time by simply going to your Twitter (or Facebook) profile page. Note that the access token returned by the OAuth protocol is application- and user-specific. The user will need to log in to multiple apps if he intends to operate on multiple OAuth-based apps. OAuth is an HTTP-based protocol for authenticating users. You don’t often have to write HTTP requests manually, even though you could (for example, to learn how things work “under the covers”). In the Microsoft .NET Framework, you can use general-purpose libraries such as DotNetOpenAuth ( or pick up ready-made frameworks for a specific social network such as TweetSharp for Twitter and the Facebook C# SDK for Facebook.

When it comes to authentication, take a look at the Azure Access Control Service. This can act as a federated identity provider and can translate multiple identity provider mappings. It can host OAuth and Security Assertion Markup Language-based tokens from Active Directory. It’s also built to work with Facebook and the new ClaimsPrincipal class in the .NET Framework.

Authenticating Users via Facebook

Let’s start with a basic ASP.NET MVC site and use NuGet to plug in the Facebook C# SDK (see Figure 2). The ASP.NET MVC sample site is enriched with a brand-new authentication controller with three methods, which I named FacebookLogin, FacebookAuthenticated and Logoff. The first two methods represent the two steps of an OAuth interaction; the Logoff method just logs the user out of the host app. Note that the Logoff action isn’t supposed to log the user out of Facebook. OAuth and the Facebook C# SDK only manage the authentication logic—persisting authentication information via cookies is still up to the ASP.NET MVC site.

Referencing the Facebook C# SDK via NuGet
Figure 2 Referencing the Facebook C# SDK via NuGet

The homepage of the site provides a link for the user to click when she wants to log in (see Figure 3). The link can simply be an anchor to an image (or a text) that points to the FacebookLogin action on the authentication controller:

<a href="/Auth/Logon" >
  <img src="@Url.Content("~/Content/Images/loginfb.png")"  
    style="border:0" alt="Sign in with FB" />

The Button to Trigger the Facebook Authentication Process
Figure 3 The Button to Trigger the Facebook Authentication Process

In a standard ASP.NET MVC site, this markup belongs to the _logOnPartial.cshtml page. Let’s have a look at the authentication controller.

In the FacebookLogin action—the name is arbitrary—you need to do a couple of things. First, you arrange the URL that, once invoked from the OAuth provider, will cause your app to complete the authentication step. In the sample app I’m considering, the URL will point to the FacebookAuthenticated action on the Auth controller. You can use the handy UriBuilder class for this kind of work:

var uri = new UriBuilder(Request.Url)
    Path = Url.Action("FacebookAuthenticated", "Auth")

The second thing to do in the FacebookLogin action is arrange the Facebook URL for login. If you use the Facebook C# SDK, here’s the code you need:

var client = new FacebookClient();
var appId = ConfigurationManager.AppSettings["fb_key"];
var returnUri = uri.Uri.AbsoluteUri;
var fbLoginUri = client.GetLoginUrl(new
    client_id = appId,
    redirect_uri = returnUri,
    response_type = "code",
    scope = "email"

The parameters you pass to the GetLoginUrl method help prepare the URL. Figure 4 describes the parameters in more detail. The action FacebookLogin ends by redirecting the user to the returned login URL.

Figure 4 Login Parameters

client_idID of the Facebook app acting as the proxy between the user app and the Facebook site. You get this unique string when you register your Facebook app.
redirect_uriURL to return to complete authentication (for example, grab identity information and create an authentication cookie).
response_typeThis can be “token” or “code,” and it refers to how Facebook returns the access token after a successful authentication. For Web sites, it should be “code,” as this ensures the access token—a sensitive piece of information—is not appended to the URL.
ScopeIndicates the additional permissions you want to request for the user. When the scope parameter is blank, the app has access to the user’s basic information such as name, picture and gender. Through this parameter, you can request the e-mail address, as well as the publishing stream to be able to post. The full list of permissions is available at

To authenticate a user via Facebook (or Twitter), you need to register a Facebook (or Twitter) app first and get some unique codes for that function. To register a new Facebook app, go to Upon successful creation of the app, Facebook gives you an app ID string and an app secret string displayed in the page shown in Figure 5.

Registering a New Facebook App
Figure 5 Registering a New Facebook App

Both the app ID and app secret are required to perform Facebook operations from within a Web site or any other type of user app. It’s common to store the app ID and app secret in the configuration file of the wrapper app:

  <add key="fb_key" value="xxxxxxxxxxxx"/>
  <add key="fb_secret" value="yyyyyyyyyyyyyyyyyyyyy"/>

The Facebook login URL does what it can to authenticate the user. In particular, if the user is currently logged in to Facebook, a request token is prepared and sent immediately to the specified return URL—in this case, this is the FacebookAuthenticated action. If no user is currently logged in on the machine, Facebook displays a classic login page. In doing so, it also lists the permissions that the app is requesting. At the minimum, permissions concern e-mail address and display name. However, they might include permission to post on behalf of the user or access to the media stream, friends, timeline and more. The user is expressly requested to approve or deny those permissions. Full permissions reference information can be found at

Finalizing the Authentication Process

To finalize authentication, you need to request and parse the access token, as shown in Figure 6. The method ParseOAuth­CallbackUrl allows you to retrieve the access code from Facebook. This code isn’t sufficient to control the Facebook account; you need to exchange it for an access token. According to the OAuth protocol, this requires another step and another HTTP request. Once your Web site holds the access token for a given user and a given Facebook app, it gains control of the Facebook account for the permissions the user explicitly granted. At the very minimum, you have permission to retrieve information about the user such as first and last name and, if allowed, e-mail address.

Figure 6 Finalizing the Authentication

public ActionResult FacebookAuthenticated(String returnUrl)
  // Prepare the return URL
  var returnUri = new UriBuilder(Request.Url) {
    Path = Url.Action("FacebookAuthenticated", "Auth")
  // Parse response to get the access code
  var client = new FacebookClient();
  var oauthResult = client.ParseOAuthCallbackUrl(Request.Url);
  // Exchange the code for the access token   
  dynamic result = client.Get("/oauth/access_token",
    new {
      client_id = ConfigurationManager.AppSettings["fb_key"],
      client_secret = ConfigurationManager.AppSettings["fb_secret"],
      redirect_uri = returnUri.Uri.AbsoluteUri,
      code = oauthResult.Code
    // Saves the token to a cookie for further access
    var token = result.access_token;
    FbHelpers.AccessTokenSave(Response, token);
    // Grab identity information using the access token
    dynamic user = client.Get("/me",
      new {
        fields = "first_name,last_name,email",
          access_token = token
    // Create the ASP.NET authentication cookie
    var userName = String.Format("{0} {1}",
      user.first_name, user.last_name);
  FormsAuthentication.SetAuthCookie(userName, false);
  // Back home
  return Redirect(returnUrl ?? "/");

If your only purpose is authenticating users via Facebook, you create the standard ASP.NET authentication cookie and you’re done. If your app wants to do more (for example, post on behalf of the user), then you need to store the access token so it can be given the same lifetime as the authentication cookie. You can save the access token to a database or to a cookie. Better yet, you can create a custom principal and store the access token as extra user data in the ASP.NET authentication cookie. In my sample app, I’m just creating an additional cookie that’s managed by the FbHelpers class (see the accompanying source code for details).

Note, though, that the access token is subject to some expiration rules. If you authenticate using server-side code (that is, send users to authenticate with the Facebook site, as discussed here), then you get a long-lived token that lasts for 60 days. If you use the JavaScript SDK and attempt a client-side authentication, then you get a short-lived token that expires after two hours. You can extend this duration to 60 days by making a second call to a specific endpoint. In any case, once the access token is expired, users need to authenticate again and reacquire a valid access token. Here’s a good way of coding that:

try {
  var client = new FacebookClient(...);
  dynamic result = client.Get("me/friends");
} catch (FacebookOAuthException) {
  // Your access token is invalid or expired.

The whole story is well-summarized at

Posting to a User’s Wall

In an OAuth scenario, when you hold the access token for a user/application pair, you can programmatically execute any of the interactive operations for which the user granted permissions to the app. To post a message to the user’s wall you need the following code:

public static void Post(String accessToken, String status)
  var client = new FacebookClient(accessToken);
  client.Post("/me/feed", new { message = status });

You call this helper method from within a controller action method. The access token string must be retrieved from wherever you saved it, whether a custom cookie, the authentication cookie or a persistent store. If you lost the access token, then for the post operation to be successful the user needs to log out and log in again. If you intend to perform tasks against Facebook, storing the access token in a way that survives browser restarts is key. Figure 7 shows the sample app that posts a message, and the user’s wall properly updated.

Posting to the Wall
Figure 7 Posting to the Wall

Next Up: Windows Presentation Foundation

To summarize, Facebook exposes a fairly rich API through which developers can integrate Facebook content and logic with their own apps. Facebook apps are certainly embedded apps living within the Facebook boundaries, but they’re also classic Web or desktop applications living externally. In this column I used the Facebook C# SDK to perform two simple but quite common operations: authenticating a user of a Web site using her Facebook account and using the pages of the site to post to the current user’s wall. In the next column, I’ll expand the set of Facebook APIs used and discuss how to achieve the same operations from within a Windows Presentation Foundation application.

Dino Esposito  is the author of “Architecting Mobile Solutions for the Enterprise” (Microsoft Press, 2012) and “Programming ASP.NET MVC 3” (Microsoft Press, 2011), and coauthor of “Microsoft .NET: Architecting Applications for the Enterprise” (Microsoft Press, 2008). Based in Italy, Esposito is a frequent speaker at industry events worldwide. Follow him on Twitter at

Thanks to the following technical expert for reviewing this article:Scott Densmore