Joel
Joel

Reputation: 6107

Facebook authentication and Ajax

I am building a Facebook application, and using the oAuth 2.0 protocol for authentication/authorization.

When a user first visits my app I am using the protocol and store the access token in order to make future requests to the Graph API. The problem occurs when the access token expires and the user is using ajax.

When the ajax request is sent I try to retrieve information from the Graph API using the access token, but since it expired I get a JSON saying the access token is invalid. Now, I can send a response back to the client saying the access token expired and on the client side I can redirect him to https://www.facebook.com/dialog/oauth to go through the authentication process again. However, since the whole process is in Ajax, redirecting the user will hurt the usability of the application.

Is there any other way I can use the protocol to get a new access token without needing to redirect the user's browser to get a new access token? Maybe something on the server side?

Upvotes: 2

Views: 1350

Answers (3)

Vladimir
Vladimir

Reputation: 2553

I'm encountering this issue as well. One solution I came up with is as follows:

  1. Create an async method called isAccessTokenValid()
  2. Invoke isAccessTokenValid() before any method that will require FB interaction
  3. If access_token has expired. save the current uri to the session, along with any form data entries (if any), and start the re-authentication process again.
  4. Once the user has re-authenticated, bring up the stored uri.

This is a bit dirty, but I haven't seen a cleaner solution yet.

Upvotes: 0

Jimmy Sawczuk
Jimmy Sawczuk

Reputation: 13614

As Rafael notes, you can ask the user for offline_access and then the token should never expire. However, in practice, the access token does expire when a user changes their password or uninstalls/reinstalls your app, so you'll need to build a way for the user to reauthenticate themselves so you can update their token. I suggest redirecting them to a login page that should (ideally) just send them right back where you tell them to go without them having to do anything, and using deep linking to put them right back in your app where they left off.

Upvotes: 1

Rafael
Rafael

Reputation: 11

You just need to ask for the offline_access permission, then your access_token will not expire.

Upvotes: 1

Related Questions