Master Facebook's OAuth process in C#


Here we'll show you how to go through the Facebook OAuth process in C#, which lets any Facebook user log in to Facebook and grant your .NET application access to their account. Our simple app simply logs users in and displays some info about their Facebook profile.

In order to follow this example, you'll need the .NET 4.5 framework and Microsoft Visual Studio 2013 (or later).

Create your C# web project

1 Log in to Temboo. If you don't already have an account, you can register for free.

2Download the Temboo C# SDK and extract the ZIP file into the directory where you keep your Visual Studio projects.

3 In Visual Studio, create a new "C# ASP.Net Empty Web Application" project. For this example, name it TembooOAuth.

4 Right-click the References folder under TembooOAuth and select Add Reference. In the dialogue box that appears, select Browse and select TembooSDK.dll located in the bin folder within the extracted Temboo SDK directory. Click OK.

5 Right-click the TembooOAuth project and select Add > New Item. Select Web Form and name the new item default for this example. You should see a new item called default.aspx appear under the TembooOAuth project; this is the ASP.Net web controller that we'll use to host our simple UI and code.

Register your Facebook App

6 Create a new Facebook app via the Facebook developer console using the Apps menu at the top of the page. Once you've created a new App, click the Settings tab on the left, select + Add Platform, and choose the Website option. Set up your Temboo callback URL by specifying the following URL as your Site URL:

https://ACCOUNT_NAME.temboolive.com/callback/

Note: you'll need your Facebook App ID and App Secret later, so copy them somewhere convenient.

Add the C# OAuth Code

7 Open default.aspx and edit the content of the HTML <body> tag to read as follows:

<body>
    <form id="form1" runat="server">
    <div>
        <%if(Request.QueryString["state"] == null) { %>
            <a href="<%=getAuthorizationURL()%>">Click here</a> to begin the OAuth process.
        <%} else { %>
            <% finalizeAuthentication(); %>
            <p>Facebook authentication succeeded! Your OAuth Access Token is:</p>
            <p><%=FACEBOOK_ACCESS_TOKEN %></p>
            <p>User info response:</p>
            <p><%= FACEBOOK_USER_INFO %></p>
        <%} %>
    </div>
    </form>
</body>

8 In the Visual Studio solution navigation tree, expand default.aspx and double-click the item called default.aspx.cs. This file contains the C# variables and methods that are referenced by your ASP page. Replace the contents of this file with:

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Temboo.Core;
using Temboo.Library.Facebook.OAuth;
using Temboo.Library.Facebook.Reading;

namespace TembooOAuth
{
    public partial class _default : System.Web.UI.Page
    {
        // Replace with your Temboo credentials.
        private static readonly string TEMBOO_ACCOUNT_NAME = "ACCOUNT_NAME";
        private static readonly string TEMBOO_APPLICATION_NAME = "APP_NAME";
        private static readonly string TEMBOO_APPLICATION_KEY = "APP_KEY";

        // Provide your Facebook App ID and App Secret.
        private static readonly string FACEBOOK_APP_ID = "YOUR_FACEBOOK_APP_ID";
        private static readonly string FACEBOOK_APP_SECRET = "YOUR_FACEBOOK_APP_SECRET";

        // The location at which this page is running, used to instruct Temboo where
        // to forward users after they click "Allow" on Facebook. The value of this
        // variable is set dynamically in the Page_Load method.
        private static string CURRENT_PAGE_LOCATION;

        // We'll use these variables to store information retrieved from Facebook
        protected string FACEBOOK_ACCESS_TOKEN = null;
        protected string FACEBOOK_USER_INFO = null;

        // This method is executed whenever the page is loaded
        protected void Page_Load(object sender, EventArgs e)
        {
            // Store the location of the current page, so that we can tell Temboo
            // to direct users back here after clicking "allow" on Facebook.
            CURRENT_PAGE_LOCATION = Request.Url.AbsoluteUri;
        }


        /// Perform the first step of the OAuth handshake with Facebook, and return the
        /// URL to which the user should be sent to allow access to their Facebook account.
        protected string getAuthorizationURL()
        {
            // Generate a unique ID that will be used to identify this OAuth transaction
            string callbackID = System.Guid.NewGuid().ToString();

            // Instantiate a TembooSession with your Temboo credentials
            TembooSession session = new TembooSession(TEMBOO_ACCOUNT_NAME, TEMBOO_APPLICATION_NAME, TEMBOO_APPLICATION_KEY);

            // Instatiate the InitializeOAuth Choreo, which is used to perform the first part of the OAuth handshake.
            // For inputs we specify the Facebook App ID, the unique identifier (callback ID) for this OAuth transaction,
            // and the "forwarding URL" to which users will be sent after they allow access on Facebook. In this case,
            // we forward the user back to this page, specifying the callback ID as a querystring parameter
            InitializeOAuth initializeOAuthChoreo = new InitializeOAuth(session);
            initializeOAuthChoreo.setAppID(FACEBOOK_APP_ID);
            initializeOAuthChoreo.setCustomCallbackID(callbackID);
            initializeOAuthChoreo.setForwardingURL(CURRENT_PAGE_LOCATION + "?state=" + TEMBOO_ACCOUNT_NAME + "/" + callbackID);

            // Run the Choreo and return the Authorization URL to which the user needs to be directed
            InitializeOAuthResultSet initializeOAuthResults = initializeOAuthChoreo.execute();
            return initializeOAuthResults.AuthorizationURL;
        }

        /// Complete the OAuth handshake, after the user has clicked "Allow" on Facebook;
        /// retrieve an OAuth access token and information about the current user's Facebook
        /// account, and store it in local variables
        protected void finalizeAuthentication() 
        {
            // Retrieve the unique ID that we are using to identify this OAuth transaction,
            // from the querystring parameter
            string callbackID = Request.QueryString["state"];

            // Instantiate a TembooSession with your Temboo credentials
            TembooSession session = new TembooSession(TEMBOO_ACCOUNT_NAME, TEMBOO_APPLICATION_NAME, TEMBOO_APPLICATION_KEY);

            // Instantiate the FinalizeOAuth Choreo, which is used to complete the OAuth handshake.
            // Provide the Facebook App ID, App Secret, and callback ID (that we generated in the getAuthorizationURL
            // method, and retrieved from the querystring) as inputs.
            FinalizeOAuth finalizeOAuthChoreo = new FinalizeOAuth(session);
            finalizeOAuthChoreo.setAppID(FACEBOOK_APP_ID);
            finalizeOAuthChoreo.setAppSecret(FACEBOOK_APP_SECRET);
            finalizeOAuthChoreo.setCallbackID(callbackID);

            // Run the Choreo, and store the Authorization Token output in a variable
            FinalizeOAuthResultSet finalizeOAuthResults = finalizeOAuthChoreo.execute();
            FACEBOOK_ACCESS_TOKEN = finalizeOAuthResults.AccessToken;
            
            // Instantiate the Facebook.Reading.User Choreo, and supply the Authorization Token
            // retrieved from the OAuth process as an input.
            Temboo.Library.Facebook.Reading.User userChoreo = new Temboo.Library.Facebook.Reading.User(session);
            userChoreo.setAccessToken(FACEBOOK_ACCESS_TOKEN);

            // Run the Choreo, and store the user information retrieved from Facebook in a variable
            UserResultSet userResults = userChoreo.execute();
            FACEBOOK_USER_INFO = userResults.Response;
       }
    }
}

9 Near the beginning of the code block you just copied, there are two variables that specify your Facebook App ID and App Secret, which are needed for the OAuth process. You should have received your Facebook credentials during the app registration process described above. Substitute your own Facebook details for the placeholder values shown below:

        // Provide your Facebook App ID and App Secret.
        private static readonly string FACEBOOK_APP_ID = "YOUR_FACEBOOK_APP_ID";
        private static readonly string FACEBOOK_APP_SECRET = "YOUR_FACEBOOK_APP_SECRET";

10 Showtime! Run the web application by clicking the "Run/Debug" button in the top Visual Studio toolbar:

Screenshot of Debug button in the Visual Studio toolbar

...and browse to the following URL. Note that the port may be different depending on what edition of Visual Studio or Windows you are running.

http://localhost: 49442/default.aspx

11 Click the link to begin the Facebook OAuth process. You should be redirected to Facebook, where you can log in and grant the application access. After doing so, you should be directed back to your application where you'll see the user profile information in JSON format. That's it!

Taking a closer look at the code

At a high level, the OAuth workflow performed by this simple application looks like this:

Let's see how these steps work in practice. When this web application runs, it executes the ASP code you pasted into default.aspx. The important part looks like:

        <%if(Request.QueryString["state"] == null) { %>
            <a href="<%=getAuthorizationURL()%>">Click here</a> to begin the OAuth process.
        <%} else { %>
            <% finalizeAuthentication(); %>
            <p>Facebook authentication succeeded! Your OAuth Access Token is:</p>
            <p><%=FACEBOOK_ACCESS_TOKEN %></p>
            <p>User info response:</p>
            <p><%= FACEBOOK_USER_INFO %></p>
        <%} %>

First, we check to see if a "state" querystring parameter has been sent with the page request. This parameter gets added after the user is directed back to your application from Facebook. If the parameter isn't present, we know that we need to start a new OAuth workflow; if it has been sent, we try to complete an OAuth handshake that has already been started.

To start a new OAuth workflow, we run the getAuthorizationURL() method, that's defined in the code you pasted into default.aspx.cs. This method generates a random CallbackID that's used to uniquely identify a particular OAuth transaction, and to retrieve the Access Token returned by Facebook from Temboo.

Next, the getAuthorizationURL() method runs the InitializeOAuth Choreo. As one of its inputs, this Choreo accepts a "forwarding URL," to which the user will be sent after visiting Facebook to allow access. In this case, we specify http://localhost:49442/default.aspx?state={YOUR_RANDOM_CALLBACK_ID} as that location. The Choreo returns the URL on Facebook where users can grant account access, which we use to construct a link.

On the other side of the if statement, we finalize the OAuth process by running the finalizeAuthentication() method that's defined in default.aspx.cs This method retrieves the CallbackID value from the "state" querystring parameter, and uses it to run the FinalizeOAuth Choreo. This Choreo completes the OAuth handshake and retrieves the Facebook Access Token, which is then stored in the FACEBOOK_ACCESS_TOKEN Finally, the finalizeAuthentication() method runs the Facebook.Reading.User Choreo, to retrieve the current user's profile from Facebook, and stores the result in the FACEBOOK_USER_INFO variable.

After running the finalizeAuthentication() method, the ASP page simply prints the values of the FACEBOOK_ACCESS_TOKEN and FACEBOOK_USER_INFO variables.

What's Next?

We're all finished! This C# application executes the OAuth flow, and retrieves information about your app's user. We also have OAuth support for many other APIs in our Choreo Library.

Once you've got your code up and running, you're ready to move on and do more. From monitoring your running applications, to moving your generated Temboo code to your preferred development environment and sharing it with colleagues, collaborators and friends - we've got you covered.

Need help?

We're always happy to help. Just email us at support@temboo.com, and we'll answer your questions.


Back