How to verify Facebook Login in the backend

Paul Bao
3 min readApr 9, 2017

When you decide to give up build a password login system on your own and select a 3rd party login system, security is the most important issue. Google has a very clear guidance in their docs for how to make login process secure in the backend.

But for the Facebook Login, their docs about how to verify it in the backend is very confusing(as of Apr 9, 2017). Even though the process is quite simple, but it still should be more clear.

  1. Get the access token

In one most public doc page, we can see “nothing is needed for you”. However this is just a marketing sentence, ignore it directly. Even though the Facebook Login SKD response with an object contains user id, username, we still need to retrieve & verify it again by using the accessToken in our own backend server.

response.authResponse.accessToken

But how to verify it.

2. app_id, user_id

Facebook explains it a little bit in the same doc page. So we need to verify the app id and user id, and “manually building login flow” page. But it still means nothing.

3. input_token and access_token

After redirect to another doc page, we can get one more clue. What we actually need to do is verify the input_token, and access_token. What might be confused here is, the input_token here actually means the access_token we get from the first step, the access_token token here actually means something else. But… So what is the access_token?

Scroll down at the same doc page, another clue:

4. app access_token

By entering into another doc page, there’re descriptions for four type of tokens. So the real full name of the second access_token in step 3 is app access_token. The next step is enter into the “obtain an app access token via a server-to-server call” doc page to know how to get it.

5. Generate app access token

Finally, we get the API. But we still need three things: app-id, app-secret, domain name of this Graph API.

6. Graph API, app-id, app-secret

Take a look at somewhere else and make a guess, the domain name of the Graph API address should be the same:

Find App-id, app-secret in My App page:

7. Start coding

Finally finally, we can start coding

#Send the first accessToken returned by Facebook SDK to backenduserToken = request.form['token']#copy clientId, clientSecret from MY APP PageclientId = xxxxxxxxxxxxclientSecret = xxxxxxxxxxxxxappLink = 'https://graph.facebook.com/oauth/access_token?client_id=' + clientId + '&client_secret=' + clientSecret + '&grant_type=client_credentials'#From appLink, retrieve the second accessToken: app access_tokenappToken = requests.get(appLink).json()['access_token']link = 'https://graph.facebook.com/debug_token?input_token=' + userToken + '&access_token=' + appTokentry:    userId = requests.get(link).json()['data']['user_id']except (ValueError, KeyError, TypeError) as error:    return errorreturn userId

Life is a puzzle.

--

--