How do you renew an expired Facebook access token? - facebook

I am working from this reference, and trying to implement the OAuth protocol to allow users to log into my site via Facebook. However, Facebook's documentation is pretty terrible and it unclear in a few key parts.
It says that authorization takes three steps:
User authentication (redirect the user to https://facebook.com/dialog/oauth?client_id=...&redirect_uri=..., and expect the redirect_uri page to be called back with a code). Works great!
App authorization (handled by Facebook, etc). Works great!
App authentication (On the callback page, grab the code you get and call https://graph.facebook.com/oauth/access_token?client_id=...&redirect_uri=...&client_secret=...&code=.... The body of the response will include an access_token we need to do stuff)
I understand that with the access_token, I can call the APIs and such. But, what happens when it expires? I could get a new one, but by this point it will be many HTTP requests later, and I no longer have the code I used to get it in the first place. Do I have to store the code along side the access_token? Or, do I have to tell the user to log in again so I get a new code to get a new access_token?
Or, am I missing a key part here? I don't need an offline_access token, as I will only be polling data in response to user actions .

When the access_token expires, the user will be seen as "logged out" by Facebook. Your app will go through the same process as the first time, but the user may not.
If the user hasn't revoked access to your app, and the user is logged into Facebook at the time, the App Authorization process will take care of itself, with no actions required by the user, and you will receive a new access_token.
If the user hasn't revoked access to your app, but isn't logged into Facebook, they will be presented with a Facebook login at the App Authorization step. They won't be asked to give your app permission again, as Facebook knows that your app id is authorized by that user.
Finally, if the user has revoked access, then they will be presented with the original request for App Authorization, and you'll follow the original flow.
Essentially, you should consider the access_token as volatile, and not bother storing it, but using the access_token you receive as part of the user login process, which is happening behind the scenes all the time, and only involving the user when they log out of Facebook or revoke access to your application.
This is different than Twitter's OAuth with which you can store and re-use it.

From the Facebook documentation linked in your question:
Once the token expires, you will need to re-run the steps above to
generate a new code and access_token, although if the user has already
authorized your app, they will not be prompted to do so again.
When the access_token expires you will need to get a new one by going back through the same steps. The user will have to log in again and you will have to get a new code and in turn, a new access_token.

Related

Is it possible to renew long lived access token in Facebook using an api call?

Facebook documentation states that
. At any point, you can generate a new long-lived token by sending the person back to the login flow used by your web app - note that the person will not actually need to login again, they have already authorized your app, so they will immediately redirect back to your app from the login flow with a refreshed token - how this appears to the person will vary based on the type of login flow that you are using, for example if you are using the JavaScript SDK, this will take place in the background, if you are using a server-side flow, the browser will quickly redirect to the Login Dialog and then automatically and immediately back to your app again.
What does it mean that the person does not actually need to login? Does not he have to pass his credentials again? If not how does FB is authenticating the user and getting the refreshed access token?
Yes but you need that the user visits your web app. Then you check for login status, if it is "connected" you will get a new short-lived token without even making the user login again. That's because the token has information about apps already authorized by user. If not the case or the user hasn't login in FB then you need to call the login function.
Once you have the token you can create a new long-lived token again.

Posting to Facebook on behalf of the user: how to handle token expiration?

I'm implementing a connect with Facebook/Twitter/... functionality on a website. The idea is that once a user connects his account with the external services our website could post messages on behalf of the user.
With Twitter there is no problem as the OAuth access_token doesn't expire. But with FB it does expire every two months, when the user logouts, changes password or explictly deauthorizes the app.
How should I handle the token expiration? For me it would be ideal if I could refresh the token automatically without bothering the user, but unless I've missed something it seems there isn't any way of doing this. So, right now I've two ideas:
The less akward way: every time the user logins to the website check if the tokens have expired and notify the user that she has too reauthorize the app.
The more akward way: every time the "post to social networks" event triggers in our website, check if the tokens have expired and ask the user to reauthorize.
The first option would be easier to implement and cleaner to the user.
So, how are you handling this situations?
Thanks!
I think that I'll trye the first option:
User logs in
The server checks if the user has already a Facebook token, if so:
Check if it's still a valid token. http://developers.facebook.com/docs/howtos/login/debugging-access-tokens/
If the token expired NOT because the user deauthorized the app BUT because the other cases we redirect the user to the OAuth endpoint.
I'll give it a try and update this answer if there is more to it.
If the user is actually interacting with your website, you should be getting a fresh access_token (read below). If you perform offline tasks related to the user using the Facebook API then you should be storing the access_token and their expiry dates. Then you need to handle expired access tokens and ask the user to interact with your app again and update your records.
You should refer to this document. Also you should be reading the Extending Access Tokens document:
Step 2. Refreshing Long-lived User Access Tokens
At any point, you can generate a new long-lived token by repeating the
original auth flow, obtaining a new short-lived token and then
performing the same exchange as above. In some cases, this newer
long-lived token can be identical to the previous one, but we do not
guarantee this will be true and your app shouldn't depend upon it.

Can I retrieve a Facebook access token if I don't store it in my database?

I have been asked to look into whether or not I can retrieve a Facebook access token from Facebook if the user had granted permission in an earlier session. The problem is that our business logic tier is maintained by a different group and is on a different release schedule from the web development group. If I were to gain an offline access token, I might not be able to store it for up to two months. For any users acquired in the meantime, is there a way that I can retrieve the token from facebook without further intervention from the user?
I would think that this might be a security hole, but one of our senior developers thinks that it is likely that facebook offers such a feature.
Thanks,
Rob
In short No.
But with the offline access request being complete.
You can request a new token without any user clicking.
You just get a new offline access token and use that. The same way as if you didn't request offline access, and the access token had expired, it doesn't explicitly say but it does work:
In addition to the access token (the access_token parameter), the response contains the number of seconds until the token expires (the expires parameter). Once the token expires, you will need to re-run the steps above to generate a new code and access_token, although if the user has already authorized your app, they will not be prompted to do so again. If your app needs an access token with an infinite expiry time (perhaps to take actions on the user's behalf after they are not using your app), you can request the offline_access permission.
http://developers.facebook.com/docs/authentication/
That way you don't have to store them at all.
Unless you actually want to perform actions when the user is not using your Application.
You'll get the access_token every time the user logs back in, offline_access or not !
You can get it in JS with FB.getAccessToken();
There is no way to retrieve (offline) access token, when the user is not actually logged in.
If you want to store the access token for a long period of time, you will be required to ask for the offline_access permission, otherwise the access token will only last a short period of time. Either way, it is best to store it in a cookie or locally as it will certainly improve your app's latency. But make sure to check its validity as often as possible.
I think the access_token means, you have the permission to do things on behalf of the user. If you must do something without user FB login, you need the offline access_token. But be careful, the offline access_token will be ignored, when the user change his/her FB password, or delete the application.
So I hope there isn't any way to get another access_token without the user permission. I think the easiest way to check the access_token to make a /me?access_token= GET request, and check the answer. If the answer is an error, the access_token not working, you have to renew it.
To get access_token from somebody in the middle of the flow is a little pain. But you can also put variables to the redirect link.
Example:
https://graph.facebook.com/oauth/authorize?client_id=API_KEY&scope=email$redirect_uri=YOUR_REGISTERED_APP_URL%3F$param
$param could be a flow info like: flow=12342323
So when your user come back the $_GET['flow'] will be 12342323.

How to check my Facebook AccessToken? How to renew it? (.NET Desktop Application)

I've created a Facebook .NET Desktop Application. On the first run, the application opens a second window with a Web Browser directed to the authorization page for my application with the required permissions from the user.
If the user authorizes my app, Facebook is redirecting me to the static login_success.html and appends the AccessToken to the Hash (#) part of the Url of the browser rendered in my second .NET Application window.
I hand that AccessToken to my main application window and do my requests to the graph api on behalf of the respective user.
That's fine, and working so far!
But, how can I
check if the AccessToken I've stored is still valid and how
can I renew an expired AccessToken without bugging the user with the second browser window (of course assuming the user hasn't revoked the authorization for my app) and how
can I recognize that the user has revoked the authorization?
check if the AccessToken I've stored is still valid?
Try and use the token against the Graph, and if it give you an error (Something like OAuthException or OAuthError), it's not valid, else it still is.
Can I renew an expired AccessToken without bugging the user with the second browser?
No that I know of. But, AccessTokens (with the Offline Access permission) don't expire. I've received an AccessToken for one of my apps almost 2 years ago and it hasn't changed or expired, so I think you should be good. They might become invalid if your App Secret changes or if the user changes their password (I'm pretty sure on that last one, but not 100%)
Can I recognize that the user has revoked the authorization?
Yes, if you query the Graph with an AccessToken that is not authorized for that function, it will give you an OAuthException. Just check for exceptions after you receive Graph data and it will let you know, for the most part, why you weren't able to receive Facebook data.
Unfortunately, if your Access Token expires you have to get the user to go through Facebook to get a new Access Token. An offline_access token does not ever expire due to time, like joe_coolish pointed out, but it does expire if the user changes their password. So your program needs recognize when a user's access token is invalid and get the user "refresh it" by going through the oauth endpoint.
Recognizing that the user's token is invalid is the same process as recognizing that the user has revoked authorization for your application. Whenever you make a graph request with an invalid access token, Facebook will give you an OAuthException saying that you don't have access.

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?
You just need to ask for the offline_access permission, then your access_token will not expire.
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.
I'm encountering this issue as well. One solution I came up with is as follows:
Create an async method called isAccessTokenValid()
Invoke isAccessTokenValid() before any method that will require FB interaction
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.
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.