Facebook OAuth 2.0 "code" and "token"

jkeesh picture jkeesh · Dec 29, 2011 · Viewed 37k times · Source

Why do you need both a "code" and a "token" in the Facebook OAuth2 authentication flow as described here: https://developers.facebook.com/docs/authentication/ ?

If you look at the OAuth dialog reference (https://developers.facebook.com/docs/reference/dialogs/oauth/), it seems like you only ever use the token to fetch information about the user, and if you specify the response_type parameter as token or code,token, then you get the token on the first time.

Why do you need to get a "code" and then use the code to get a "token" as opposed to getting the token directly?

I guess I'm misunderstanding something basic about how OAuth works, but it seems you avoid the request to https://graph.facebook.com/oauth/access_token entirely if you get the token the first time with the dialog.

Answer

Kris Subramanian picture Kris Subramanian · Apr 27, 2016

Let us take a simple example to differentiate authentication code vs access token.

You as a user want to try a new Facebook app called Highjack. So you click on the application and the Highjack app. asks you to log into your Facebook account. When you are done Facebook generates a authentication code for you.

This code is then passed to the Highjack server which uses its own FB client id, FB secret and your authentication code to get a access token.

In the above example the authentication code is confirming you as a user is a valid FB user. But the second steps says "you as a FB user is giving access to the Highjack app for certain resources".

If the Highjack app wanted implicit grant (i.e direct access token), then the access token would be visible to you also since it being exchanged with the browser. This means you can now call all Facebook APIs on behalf of Highjack using the access token. (You can only use the access token to get your personal information but Facebook has no way of knowing who is calling their APIs.)

Since we have 2 parties (You and Highjack) authenticating with Facebook we have this 2 fold mechanism.