Obtain Access Tokens - nov/fb_graph2 GitHub Wiki

Obtain Access Tokens

JS SDK

JS SDK is the most common & easy-to-use tool to implement FB login flow on Web sites.
For JS SDK usage, read the official FB documentation.

In FB.init() call, you need to set cookie option true to parse FB session in your server-side (aka ruby world).

FB.init({
  appId      : '{your-app-id}',
  cookie     : true, // This is MUST.
  xfbml      : true,
  version    : 'v2.3'
});

Once you get a FB session (a.k.a. “signed request”), you can parse signed cookie provided by JS SDK and obtain an access token using this gem as below.
In FbGraph2::Auth#from_cookie, this gem exchange code included in the signed cookie with an access token, so this is a kind of OAuth2 code flow.

auth = FbGraph2::Auth.new(FACEBOOK_APP_ID, FACEBOOK_APP_SECRET)
signed_request = auth.from_cookie cookies
signed_request.access_token

JS SDK also provide an access token on client-side (a kind of OAuth2 implicit flow), but I don’t recommend to use it on server-side because of 2 reasons.

1. Access tokens obtained on client-side are short-lived (5 min), ones obtained on server-side are long-lived (6 months)
2. Sending access tokens obtained via implicit flow to server-side often causes "Token Substitution Attack". Code flow is always better from security point of view.

If JS SDK doesn’t match your use-case, raw OAuth2 flow can be an alternative.

iOS/Android SDK

With Native SDKs, you would need to send access tokens from your native app to your backend server.
Since it is a kind of OAuth2 implicit flow, you need to avoid "Token Substitution Attack" by yourself on server-side.

There are 3 ways to avoid the attack.

Debug Token API

You can use Debug Token API as below.
If this call doesn’t raise any exceptions, you are safe.

auth = FbGraph2::Auth.new(FACEBOOK_APP_ID, FACEBOOK_APP_SECRET)
auth.debug_token! 'obtained-access-token'

GET /app endpoint

app = FbGraph2::App.app('obtained-access-token').fetch
if app.id == 'your-app-id'
  # you are safe
else
  # you are attacked!!
end

Extending Access Token Lifetime

If this code don’t cause any exceptions, you are safe.

Raw OAuth2 Flow

Use rack-oauth2 gem, omniauth-facebook gem etc.
Since FbGraph2::Auth is a sub-class of Rack::OAuth2::Client, you can use it as described in rack-oauth2 documentation.

Using rack-oauth2 gem, don’t forget to verify state parameter described in OAuth2 Core RFC.
It’s MUST when using OAuth2 for authentication purpose to avoid CSRF attacks.
omniauth-facebook does CSRF protection by itself.

Once you obtained access tokens, you can use this gem using the obtained access tokens.

auth = FbGraph2::Auth.new(facebook_app_id, facebook_secret_key)
auth.access_token!

FB iframe Apps

auth = FbGraph2::Auth.new(FACEBOOK_APP_ID, FACEBOOK_APP_SECRET)
signed_request = auth.from_signed_request params[:signed_request]
signed_request.access_token
⚠️ **GitHub.com Fallback** ⚠️