Saturday, July 12, 2014

Facebook Access Tokens with Later Expiration Date

In previous posts I wrote about the connection of C# and Facebook (check for that the corresponding label).
In some of those (for example Publish Posts) we needed a so called access token, which grants our application the needed rights. In this post I want to examine these with a little bit more detail, because Facebook shortened the validity of these, they expire after a while.
As you can read hier, there are different kinds of access tokens, e.g. app access tokens and user access tokens. App access tokens are needed for every application which uses Facebook and can simply be acquired by submitting app ID and app secret.
But if one wants to perform user specific actions like the previously mentioned posting of status updates, you need a user access token, which is authorized by the user. With this kind of token we want to deal here.
Token of this kind can be acquired manually via the Graph API Explorer, for which we log on with our desired user account. Then we chose the application we need the token for in the dropdown list above and click "Get Access Token". In the new window we chose the needed permissions and confirm, the token string is then displayed in the textfield. This string we can now use in the program code and with that, for example, post stuff.
In previous posts I with that let the topic rest, since the tokens were valid for a pretty long time. Facebook though now changed this, tokens are now only valid for 1 - 2 hours. The expiration date and other information can be checked with the Facebook Debugger.

If we now write an application which works with Facebook, we have to request a new token manually every 1 - 2 hours. Of course this is not feasible. Since the creation of a token via code is not so easy, I chose the following variant: We once create another token out of the one created above, which is significantly longer valid and pass this to the application.
Regarding this topic here there is a help page of Facebook, in which multiple alternatives are proposed, we use the fourth. As described there, the calling of the following address in the browser leads to the creation of a new access token, which is then displayed:

https://graph.facebook.com/oauth/access_token?
client_id=APP_ID&
client_secret=APP_SECRET&
grant_type=fb_exchange_token&
fb_exchange_token=EXISTING_ACCESS_TOKEN
In this call APP_ID has to be replaced by the app ID, APP_SECRET by the app secret and EXISTING_ACCESS_TOKEN by the short lived token created above. The token created in this way then has a validity of about 2 months.

No comments:

Post a Comment