Friday, June 8, 2012

What is the correct way to refresh Facebook OAuth2 access token after it expires?


As I understand it, this is the basic process for new Facebook iframe canvas apps using the OAuth2 API in a nutshell:



  1. Redirect to (or have user click link to) app's authorization URL

  2. User authorizes and is redirected to your callback URL

  3. Callback uses "code" parameter to get a access token

  4. Access token is used with Graph API to pull or push information



The problem is that access tokens expire relatively quickly and need to be "refreshed", so my questions are 1) how do you detect that the token has expired aside from trying to use it and simply getting an error? and 2) what is the best practice for obtaining a new token?



Currently, I just detect that there was an error trying to get the user's information with their access token, then redirect to the authorization URL again -- since they already authorized the app a blank page flashes by and they are redirected back to my app callback where I get a fresh token. It's so clunky I can't believe this is the proper method.



Note: this question may be similar to or the same as how to refresh an oauth token when using the Facebook iPhone SDK , but I am not using iOS SDK for iPhone, just a regular web application with iframe.


Source: Tips4all

1 comment:

  1. 1) the only way to tell if a cookie is valid is to use it and catch the error if it is expired. There is no polling method or anything to check if a token is valid.

    2) To get a new token, simply redirect the user to the authentication page again. Because they have already authorized your app they will instantly be redirected back to your app and you will have a new token. They won't be prompted to allow since they have already done that.

    In short, there are not tricks to this. You are already doing it correctly.

    ReplyDelete