Facebook User access token

User access token

In order to access any data on behalf of a user, you must first create a Facebook app. You can see a list of your applications at developers.facebook.com or simply create a new one. However before you can create any applications, Facebook requires that verify your Facebook account (enter your phone number, receive a pin code, that sorta thing).

Once you have created the desired app for accessing the API and filled in the basic information, you're almost ready to go. You should also fill out the Website with Facebook Login field with a callback URL that users are redirected back to after logging in.

Setting up the login

Below I will explain how to set up a login page so users can allow your app to access their data. Even if you only need a user access token for your own Facebook account, you'll still need to follow this process.

The first step is to redirect the user to the Facebook authentication dialog along with information identifying your application. Skybrud.Social has a class named FacebookOAuthClient for this purpose. You can initialize it by doing something like this:

FacebookOAuthClient client = new FacebookOAuthClient {
    AppId = "Your application ID",
    AppSecret = "Your application secret (keep this secret)",
    RedirectUri = "The return URI (where users should be redirected after the login)"
};

When you have initialized an instance of this class, you can redirect the user to the authorization page at Facebook.com. If the user is currently not logged in with Facebook, he/she will be prompted with the login dialog. When the user is logged in and hasn't already authorized your application (or the scope has changed), the user will be prompted with the authorization dialog. If the user authorizes your application he/she will be redirected back to the specified redirect URI. You can generate the authorization URL like this:

string authorizatioUrl = client.GetAuthorizationUrl(state, FacebookScope.ReadStream + FacebookScope.Email);

Or simply:

string authorizatioUrl = client.GetAuthorizationUrl(state, "read_stream", "email");

The first parameter is the state of the request. It is specified for security purposes, and should be something that uniquely identities the user on your site. Any other parameters specify the scope (or permissions) of your application. If you're not sure what scope to specify, you can read more about Facebook permissions or not specify a scope at all:

string authorizatioUrl = client.GetAuthorizationUrl(state);

When the user has successfully authorized your application, he/she will be redirected back to your redirect URI with your previously specified state and an authorization code in the query string. Once you have obtained an authorization code for a user, you should exchange it for an user access token:

string accessToken = client.GetAccessTokenFromAuthCode(Request.QueryString["code"]);

Should the user choose to cancel the login, he/she will still be redirected back to your redirect URI, but with the parameters error_reason, error and error_description in the query string. You can read more about it on this page.

Accessing the API

Once you have obtained an access token for the user, you can start using the API through the FacebookService class:

// Initialize the service from the access token
FacebookService service = FacebookService.CreateFromAccessToken(accessToken);

// Get the posts from the authenticated page
FacebookPostsResponse response = service.Posts.GetPosts("me");

// Loop through the posts
foreach (FacebookPost post in response.Body.Data) {

    // Do something with the post

}

When you have an user access token, the name me is a reference to the current user.

Full example

Below you can see a full example of the steps explained above implemented in a Razor partial view. Since this is just a very basic example, it will simply print out the access token after a successful authentication. Obviously you should store the access token somehow or further authenticate the user with your underlying system.

@using Skybrud.Social.Facebook
@using Skybrud.Social.Facebook.OAuth
@inherits WebViewPage
              
@{
    
    // Initialize a new instance of the OAuth client
    FacebookOAuthClient oauth = new FacebookOAuthClient {
        AppId = "Your application ID",
        AppSecret = "Your application secret (keep this secret)",
        RedirectUri = "The return URI (where users should be redirected after the login)"
    };

    // Read some input from the query string
    string code = Request.QueryString["code"];
    string action = Request.QueryString["do"];
    string error = Request.QueryString["error"];
    string errorCode = Request.QueryString["error_code"];
    string errorDescription = Request.QueryString["error_description"];


    // Handle the state when the user clicks our login button
    if (action == "login") {

        // Get the redirect URI (if present)
        string redirect = (Request.QueryString["redirect"] ?? "/");

        // Set the state (a unique/random value)
        string state = Guid.NewGuid().ToString();
        Session["Facebook_" + state] = redirect;

        // Construct the authorization URL
        string authorizatioUrl = oauth.GetAuthorizationUrl(state, FacebookScope.Email);

        // Redirect the user to the OAuth dialog
        Response.Redirect(authorizatioUrl);
        return;

    }

    // Handle if an error occurs during the Facebook authentication (eg. if the user cancels the login)
    if (!String.IsNullOrWhiteSpace(error)) {
        <div class="alert alert-danger">
            <strong>Login failed</strong><br />
            @errorDescription (code: @errorCode)
        </div>
        return;
    }

    // Handle the state when the user is redirected back to our page after a successful login with the Facebook API
    if (!String.IsNullOrWhiteSpace(code)) {

        // Get the state from the query string
        string state = Request.QueryString["state"];

        // Validate state - Step 1
        if (state == null) {
            <div class="alert alert-danger">No <strong>state</strong> specified in the query string.</div>
            return;
        }

        // Validate state - Step 2
        string session = Session["Facebook_" + state] as string;
        if (session == null) {
            <div class="alert alert-danger">Session expired?</div>
            return;
        }

        // Remove the state from the session
        Session.Remove("facebook_" + state);

        // Exchange the auth code for an access token
        string accessToken = oauth.GetAccessTokenFromAuthCode(code);
        
        // Print out the access token to the user (we really shouldn't do this in a live environment)
        <div class="alert alert-info">
            <strong>Access token:</strong> @accessToken
        </div>

        // Initialize a new instance of the FacebookService class so we can make calls to the API
        FacebookService service = FacebookService.CreateFromAccessToken(accessToken);

        // Make a call to the API to get information about the authenticated user (aka "me")
        FacebookUserResponse response = service.Users.GetUser("me");

        <div class="alert alert-info">
            <strong>ID:</strong> @response.Body.Id<br />
            <strong>Name:</strong> @response.Body.Name<br />
            <strong>Email:</strong> @response.Body.Email
        </div>

        return;

    }

    <a href="?do=login" class="btn btn-primary">Login with Facebook</a>
    
}