Facebook - when does the SDK refresh the auth token? - facebook

According to the Facebook docs, mobile SDKs generate long lived tokens which are refreshed once per day when the person using your app makes a request to the Facebook servers. For the javascript SDK, short-lived tokens are generated and are refreshed periodically.
I'm curious as to what is meant by "the person using your app makes a request to the Facebook servers". Which calls specifically will cause the token to be refreshed? Or more importantly, which calls won't? Is it enough to check the login status or is something more active required? What I'm really interested in is keeping the token alive (or getting a new one) without sending the user back through the login flow, or doing anything that's particularly active with Facebooks APIs.
Thanks!

According to Facebook SDK Docu
Once a token expires ("auto" extend of Facebook SDK Token)
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
THERE IS no keep alive functionality in Facebook SDK.
User access tokens come in two forms: short-lived tokens and long-lived tokens. Short-lived tokens usually have a lifetime of about an hour or two, while long-lived tokens usually have a lifetime of about 60 days. You should not depend on these lifetimes remaining the same - the lifetime may change without warning or expire early. See more under handling errors.
long-lived = 60 days
Short-lived = 2 hour
Also according to Facebook SDK Docu
Mobile apps that use Facebook's mobile SDKs get long-lived tokens.
Once you force a user for a new oAuth/login, he will receive a new token. The old one will not expire. You are able to check the loginStatusby FB.getLoginStatus. No need for a keep alive.

The SDK will refresh the access token for you when an actual graph request is made (up to once a day). Any time the token is updated, the AccessTokenTracker will be notified, so you can register a tracker if you want to be notified of updates (e.g. for sending to the server).
If you only make graph requests from your server, then you'll need to handle expiration from there, and either try to extend, or prompt your user to do SSO again to get an updated token.

Related

Facebook oauth2 API refresh tokens

I am building an application that does not have a client interface.
At the setup step: The user logs into the server throught a browser once using oauth, and the server makes sure that the client is identified.
From this point on, no browsers are invlovled. It all happens in the background.
It then keeps acting on behalf of the user for as long as the user can be validated.
That means that once in a while, my server needs to call the oauth provider to validate the user still exists.
Until now, I have only used google oauth: Once in a while, I would call the refreshtoken api, and get a new token indefinitely from the server side. (you need to ask for "offline access" when you get the user token).
Now I would like to use facebook as well, but reading their APIs, I see no mention of a possibility for a server to refresh it's tokens:
https://developers.facebook.com/docs/facebook-login/access-tokens/refreshing/
It looks like it all has to be done from the client device.
As I have no client device, does this mean that I cannot write this sort of app with facebook?
I think your scenario can be covered through Facebook's mechanism. But you need to support a re-login if some error occur while using long lived access token. This can happen due to security measure taken by Facebook (ex:- data breach, cryptographic breach) or when user revoke tokens or change password or when tokens are not used for a longer time.
Steps to follow (According to their docs),
Obtain a User access token
These are short lived
Short-lived tokens usually have a lifetime of about an hour or two
Exchanging Short-Lived Tokens for Long-Lived Tokens
These have life span of around 60 days, even when they are not used.
long-lived token generally lasts about 60 days.
Basically, once you obtain a long lived token, you can use it from the server application. During this process, you required a client which used browser only to obtain short lived access token.
But as previously mentioned, these tokens can expire,
These tokens are refreshed once per day, when the person using your app makes a request to Facebook's servers. If no requests are made, the token will expire after about 60 days and the person will have to go through the login flow again to get a new token.
So you will require to obtain new ones by going through above two steps.

Facebook: Refreshing long-lived access token automatically

I'm storing long-lived access tokens for users of my application that have associated their Facebook accounts to it. Since the demise of the offline_access tokens, these long-lived tokens have an expiry date of "about 60 days." However, they can refresh themselves when the user interacts with Facebook. According to the documentation:
These tokens will be refreshed once per day when the person using your app makes a request to Facebook's servers. If no requests are made, the token will expire after about 60 days and the person will have to go through the login flow again to get a new token.
What I'd like to know is what constitutes making a request to Facebook's servers. Does the user have to log in to the Facebook website, mobile app, or use a Like button somewhere? Or does my application making a request on behalf of the user count as well?
Also, when the tokens are refreshed, are they refreshed for another 60 days? Or are they refreshed for a smaller duration?
I wasn't able to find these specific answers in the documentation or in other questions asked here, so thanks in advance to anyone who might have more details.
Every time you use Facebook SDK so it makes any Graph API call, tokens will be refreshed. You can see this in their source code, in AccessTokenManager there is function extendAccessTokenIfNeeded(), and that function is called inside GraphRequest in function executeConnectionAndWait().
You can also manually refresh tokens by calling:
AccessToken.refreshCurrentAccessTokenAsync();
I found one exception to this. Only sso tokens can be refreshed, which means if user logged in to your app via facebook app. If user logged in via browser, token will remain the same.
The previous line to the one you pasted is important:
Native mobile applications using Facebook's SDKs will get long-lived access tokens, good for about 60 days
The section you pulled out refers only to iOS and Android apps using the Facebook SDK - the SDK makes an API call to extend the token, which will only work from the SDK and for tokens produced by the native mobile SDKs-
Other apps (e.g websites, apps on facebook.com) need to use the login flows documented elsewhere in the documentation and require the user to be logged into Facebook in their browser

Handling an expired long lived access token, server side - facebook

In my web app, I need to post on users facebook feed while they are offline. I already store long lived access tokens for the users. But these tokens also expire after 60 days.
The FB docs mention that it is necessary to redirect users to the login flow to get a renewed access token.
I was thinking of checking the facebook session validity of user, whenever they login to my app and to give them the option of re-authenticating facebook in case their access token has expired.
However this will involve user interaction if the user is not currently logged in to his facebook account.
Are there any alternative solutions to look at. Also, how do sites like Quora manage posting to user's wall, without needing to re-authenticate facebook after every 60 days.
PS - I am using the latest facebook php sdk.
Simple Answer: It is not possible to extend the Access Token on the server. It would make the whole concept void.
Earlier there was a permission called "offline access", but they changed it to an extended token with maximum 60 days to avoid those things. You should NEVER post anything on the wall of the user without his authorization, for every single post. You are not allowed to autofill/prefill the message parameter anyway (see Facebook terms), it always must be 100% user generated.
About Quora: i donĀ“t know what exactly they are doing, but i assume they refresh the Access Token whenever the user goes to their website.

How to extend Facebook User Access Token using PHP SDK?

I have this code:
$facebook->api("/oauth/access_token?grant_type=fb_exchange_token&client_id=".$facebook->getAppId()."&client_secret=".$facebook->getAppSecret()."&fb_exchange_token=".$user->getFacebookAccessToken());
it does not throw any exception, but it returns null. I am trying to extend a short-lived Facebook User Access Token to be a long-lived Facebook User Access Token. However, after I have generated a new token and calling this request while the new token was still alive, I have waited for a few hours and started a browser where I was not logged in with my facebook account. Then I have logged in with a test user (to the application, not to Facebook), but unfortunately it was directing me to the Facebook login, which means that the Facebook User Access Token was somehow invalidated.
I was working based on the doc found here.
So, can someone enlighten me how should I send the request so Facebook will really extend the token's life cycle? Also, I am not sure how can I determine whether I have successfully extended the life cycle of a Facebook User Access Token. (I am not a Facebook fan, to say the least and I am new to the Facebook API too).
Thanks, guys.
EDIT:
I have read this article and copied the setExtendedAccessToken method into my class with a few modifications to support my logic. Now the code which tries to extend the life cycle of the User Facebook Access Token is as follows:
$facebook->setExtendedAccessToken($user->getFacebookAccessToken());
Now it returns an array of two elements, the token and the expiry date. The expiry date is "5174078". I believe I am on the right track to solve this problem, am I?
Here's what I think you should be doing:
An FB user, logged in, comes to your site and you get a short-lived token for them via the client side flow in the Javascript SDK or a long-lived token via the server-side flow with the PHP or some other SDK (it appears you are doing the first of these already)
If it was a short-lived token, extend it and get a long-lived token via the API call to exchange the token (it appears you're doing this too)
Save long-lived token to your database (not sure if you're doing this)
When the user comes back to your app at some other point, logs in to your app via your own login system, but is not logged in to Facebook, you use the cached token from your database in ->setAccessToken() and then make calls to the Facebook API on their behalf
i think step 4 is your problem; I suspect you're seeing the user is logged-out of Facebook and sending them through the Facebook auth process again instead of having them log into your app via your own login mechanism, and reusing the token you stored before.
This is perfectly fine, but in that case there's no need for you to store the tokens, and you could do this all 'live' and require your users to be still logged into Facebook to fetch a new token 'live' instead of caching the token you obtained on their previous visit to your app.
Just as an FYI cause I've been stumbling around with access token for the last 45 minutes. Via facebook's documentation:
https://developers.facebook.com/docs/roadmap/completed-changes/offline-access-removal/
which seems to be a little dated, I was able to manually extend my existing short lived access token with:
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

Unable to get a long-lived Facebook Access Token with Server Side OAuth Fow

I am trying to get a long-lived Facebook Access Token so my java servlet app can monitor and retrieve messages and such for my users without reauthorizing every hour or two.
I am using the server side oauth flow and have everything working perfectly but am not able to get tokens that are good for more than a day.
The first user authorization call is:
https://www.facebook.com/dialog/oauth?client_id=-----&client_secret=-----&scope=read_mailbox,manage_pages&force=true&state=-----&redirect_uri=http%3A%2F%2F127.0.0.1%3A7101%2FeStarGlobal-eStarGlobal-context-root%2FOAuthCallback%3BJSESSIONID%3DvS9lP9JcF3B86zD99KVNGXzn2snKRl4V48lkJQD51cvXhpnLsT06%21-281618363%211342018780176%3FAuthSource%3D1%26AuthType%3D1%26EmployeeId%3D97
The user authorizes my app and I receive the code on my callback URL and call for my access token:
https://graph.facebook.com/oauth/access_token?client_id=-----&client_secret=-----&code=---code from above---&redirect_uri=http%3A%2F%2F127.0.0.1%3A7101%2FeStarGlobal-eStarGlobal-context-root%2FOAuthCallback%3BJSESSIONID%3DvS9lP9JcF3B86zD99KVNGXzn2snKRl4V48lkJQD51cvXhpnLsT06%21-281618363%211342018780176%3FAuthSource%3D1%26AuthType%3D1%26EmployeeId%3D97
I receive a valid token that is good for about 6800 seconds and try to exchange it for a longer lived token:
https://graph.facebook.com/oauth/access_token?client_id=-----&client_secret=-----&grant_type=fb_exchange_token&fb_exchange_token=---token from above---
I get the same token with a slightly shorter expiration seconds.
I have enabled: Remove offline_access permission on my Facebook App page. I do not have an Enhanced Security Dialogs setting.
I changed the App Type from Web to Native/Desktop and that extends the expiration to about 89000 seconds or a day.
Any ideas would be greatly appreciated!
You say ' I do not have an Enhanced Security Dialogs setting.'
If that means you're not using the enhanced dialog - you need to to get the long-lived tokens.
If that means you don't have the option there to switch between enhanced and the old version, then it's probably not relevant - you should have the new one then