Authenticating using Facebook

I had figured out how to authenticate users using Facebook a couple of months back. But I didn’t document it, and so yesterday I again wasted my time figuring it out. So here is the brain dumb so that I won’t waste my time again at the time of need. 🙂

Prerequisite: Create an app using Facebook Developer account and create the necessary App ID and App Secret keys.

If you are testing out your app and you are running it locally, the site URL should be something like http://localhost:8090/

At the client side:

Asking for permission and login:

  • Use the SDK provided by facebook
  • I am assuming Javascript SDK is used. Inspect the response returned.
    • Send the authResponse.accessToken and authResponse.userID to the server for authentication.

At the server side:

Authentication:

  • Verify the user by calling the Facebook Graph API:

https://graph.facebook.com/debug_token?input_token={authResponse.accessToken}&access_token={app_id|app_secret}

Response:

{
    "data": {
        "app_id": "1234",
        "application": "testapp",
        "expires_at": 1426158000,
        "is_valid": true,
        "scopes": [
                "public_profile",
                "email"
                ],
        "user_id": "111112223333"
     }
}

  • input_token is the authResponse.accessToken we obtained as a result of the login process from Facebook.
    access_token is the App Token. It can either be generated as mentioned in this link. Or instead of generating we can use the concatenated form: {app_id} + ‘|’ + {app_secret}. I have used this second form above.
  • Verify the JSON obtained and check whether “is_valid” == True and “user_id” == authResponse.userID to make sure user is a valid one.
  • The authResponse.userID returned can be used to identify the user and used instead of username to lookup users.

Using the Graph API:

Suppose we want to obtain the user’s email Id at the server side:
Call the API as follows:
https://graph.facebook.com/{authResponse.userID}?fields=email&access_token={authResponse.accessToken}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s