KTL SOLUTIONS

How to Get Facebook Data using OAuth 2.0

Share this post

In my previous article, I gave an overall description of OAuth by comparing it to our everyday life scenario. In this article, I will dive in to the details of implementing OAuth to get data out of Facebook.

Where can you get Facebook data?

Facebook provides a low-level HTTP-based API called ‘Graph API,’ which can be used to get data in and out of Facebook. A tech giant such as Facebook is very serious about protecting their User’s data and as such would not provide information without proper authentication.

Who is the logged in User? How can you tell?

Let’s make an HTTP GET request to one such Graph API endpoint (in other words, copy paste this url https://graph.facebook.com/me in a browser)

The response you will see on the screen is:

So, it looks like Facebook failed to authenticate you because it doesn’t know who you are at this point. Now go to Facebook and login to your account to see your Facebook page. Open another tab and paste https://www.facebook.com/, this time you will not need to login again. Login is managed across multiple tabs and windows.

One more time, open a new tab and this time copy paste https://graph.facebook.com/me. Since you are already logged in, you are probably expecting Facebook to recognize you. But you will see the same response as before – authentication failed. Hmm … why?

This is because HTTP is stateless. The HTTP request knows nothing about logged in users unless you pass that information along with it. In the world of web programming (the regular Facebook website), there are ways to maintain information about who is logged in using cookies, session variables, Query string, etc. But GRAPH API is a REST endpoint, which knows nothing about cookies and sessions.

We can probably pass username and password as Querystring, but it is highly vulnerable to pass such sensitive information over the net. Even with encryption it is not safe enough. And would you trust the provider with your password? What if they are saving it somewhere for future use? Even if they hash the passwords and save it safely in their database, what if they get hacked and your password is leaked? This is where our Hero OAuth enters.

OAuth 2.0 and Graph API

Graph API relies on OAuth 2.0 for authentication.

OAuth grants a secured, limited, token-based access to a resource. So instead of passing your username and password, you will pass a Token. A token is created for a specific Client or Application. A token provides the following information:

  • Who is the logged in user?
  • Which Application is making the request?
  • What is the scope of the request? What resources can be accessed? Public profile, Friends list, photos, etc.

Now, when we call the Graph API with this special token, we should see a positive JSON response.

https://graph.facebook.com/me?access_token=mytoken

{

“name”: “Minal Wad”,

“id”: “1001”

}

Tokens, tokens and tokens … it’s all about tokens. But how can you get them?

Method 1: The Old Fashion way

Follow these exact steps to get an Access Token for a logged in Facebook User.

Step 1: Create a Developers Facebook App

Login in to Facebook for Developers with your credentials and create your First application.

On successful creation, you can add various products. We are going to pick Facebook Login.

When you land on this screen, cancel out of here by clicking Settings.

Set the redirect URL with an existing URL. For this example I am going to use https://www.facebook.com/connect/login_success.html/ but you can use your existing website URL where you want to redirect the call.

Obtain the following information and save it somewhere.

App Id/Client Id

App Secret

Redirect URL

Encoded Redirect URL (use any online URL encoder e.g. https://meyerweb.com/eric/tools/dencoder/ )

Step 2: Hit the Authorization endpoint (in the Browser)

Configure your Http Request as follows:

https://www.facebook.com/dialog/oauth?client_id=myclientid&redirect_uri=encodedRedirectURL

After a successful call, the redirect URL page will load. Copy the url from the address bar and save the Code.

https://www.facebook.com/connect/login_success.html?Code=Akfduhe…..

Code = A big alphanumeric number (Save this)

This code is only good for a limited time period, just long enough to get the Token.

Step 3: Hit the Token endpoint (in the Browser)

Configure your Http request as follows:

https://graph.facebook.com/v2.4/oauth/access_token?redirect_uri=encodedURL &client_id=myclientid&client_secret=myclientsecret&code=mycode

Access Token = Big alphanumeric number (Save this)

Step 4: Hit Graph API using Access Token

https://graph.facebook.com/me?access_token=mytoken

Or you can formulate a Curl request as follows to make an Http Request.

curl -H “Accept: application/json” -H “Authorization: Bearer access_token” “https://graph.facebook.com/me”

The Response of the Http Request will be a JSON

{

“name”: “Minal Wad”,

“id”: “1001”

}

Method 2: Using Graph API Explorer

Graph API Explorer is a very useful tool when you want to work with Graph API. Browse to https://developers.facebook.com/tools/explorer .

Using this tool you can create an Access Token and start hitting the Graph API end points instantly.

If you select permissions to access anything other than basic data (email, public profile) then your App will be sent to Facebook for review. It needs to clear a review process where Facebook will make sure that your App is authentic.

Select ‘Email’ permission.

Next, you will see an OAuth authorization screen, asking your permission to give access to your selected resources.

Using this token, you can now hit Graph API end points.

Login with Facebook

Since getting token the Old fashion way is kind of tedious, there are various redirects, and steps, so to make it easy, Facebook created a product or SDKs which makes working with Access Tokens a lot easy.

For Web development, there is a JavaScript SDK, which enables people to sign into a website with their Facebook credentials. You will simply have to drop small piece of JavaScript code in your HTML to include the whole SDK.

Using this SDK, you can have users

  • Check Login Status
  • Login In using Facebook credentials
  • Log Out

Go back to the Facebook App that you created earlier, but this time go to ‘Quickstart’ under Facebook Login Product.

Pick web as your platform.

Go through the various steps of the wizard that guides you through the whole set up.

I don’t have all the screens pasted here, but basically it will take you through the whole set up, and the flow of events is as follows:

  • FB login is triggered when either user tries to browse your website that requires login or ‘Log In’ button is clicked.
  • Using JavaScript SDK method FB.getLoginStatus, Login Status is checked.
  • If a user is not Logged in, then using JavaScript SDK method FB.login() either a Login Dialog is opened, or user is shown a ‘Login to Facebook’ button.
  • Facebook OAuth process then kicks in and takes over.
  • Using method FB.getAuthResponse, Access Token can be retrieved and saved.
  • If Log Out button is clicked, then FB.Logout() is used to log user out.

Short-Term Tokens and Long-Term Tokens

Access Tokens are short-lived (1-2 hours) and long-lived (about 60 days).  Access tokens generated via web login are short-lived tokens, but you can convert them to long-lived tokens by making a server-side API call along with your app secret. Mobile apps that use Facebook’s iOS and Android SDKs get long-lived tokens by default.

Few important things about Graph API

Graph API is named after a Data Structure called ‘Graph.’ A Graph has nodes and edges that connect nodes. Facebook ideology is based on Graphs. User, Photo, Comment, etc. represents a ‘Node’. A user is linked to another user via a Connection which can be compared to an ‘Edge’. Fields are properties of a Node. Graph API lays out information based on this terminology, hence the name.

Need Help? Call KTL.

Don’t let your OAuth hold your business back. KTL Solutions is a Microsoft certified partner that can help you transform your business through the power of technology. We do more than just implement or upgrade your systems. We add value to your business by understanding its unique qualities and needs.

Interested in working with KTL? Get in touch with one of our business consultants today.

Related Posts

Checking Your CMMC Progress

Written by Alec Toloczko With Cybersecurity Maturity Model Certification (CMMC) requirements on the horizon, it’s crucial for organizations handling Controlled Unclassified Information (CUI) to adhere

Read More »