Handling an expired long lived access token, server side - facebook - 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.

Related

Facebook Tokens - I created a never-expiring token, but how?

I have been trying to create a never-expiring Facebook Token (ideally programatically) and have not been able to do so, then, without really trying, on a different Facebook Application, I managed to create a token which, according to
https://developers.facebook.com/tools/debug/accesstoken?version=v2.5&q={TOKEN}
will never expire and I can't replicate it on any other Facebook Apps or for any other Facebook Tokens.
I can programatically (PHP) take the short lived token (1/2 hours) and extend it to 60 days, but I wanted to ideally get a never-expire token.
I guess I'm not asking how I managed to do it, but I can't find any explanation or documentation nor reason as to why I was able to achieve this for one token, but not any others.
Is it something in the App itself while it was created? Is there actually a way to get a never-expiring token, even though I've followed many of the guides online yet can only get a 1/2 hour token converted to 60 days?
Is there actually a way to get a never-expiring token
No, not really. Even what you think is a never-expiring token can expire - f.e. if the user who created it changes their account password.
I guess I'm not asking how I managed to do it, but I can't find any explanation or documentation nor reason as to why I was able to achieve this for one token, but not any others.
It is not documented, because Facebook wants you to use the 60 day tokens, when you app is acting on behalf of a personal user profile. They removed offline_access permission ages ago, specifically so that apps the user has long forgotten about can’t act on their behalf or still access their data any more.
So if you are writing an app that acts on behalf of users, you should really rather make do with the 60 day token - that should be enough for most cases.
Now what you are seeing with your token here, is a side effect of how Facebook has implemented extended page access tokens. Those do not have a default expiry - but they need to be invalidated when the user is removed as a page admin. Therefor, they are internally tied to the user token that was used to request the page token. User token gets invalidated - page access token becomes invalid together with it. And that in turn requires that the user token does not automatically expire after 60 days.
So, when you extend a user token that includes manage_pages permission, you will get an extended token with “unlimited” validity. But, again, that is a side effect of current implementation only, and can change in the future.

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

Is this process correct for maintaining long-lived Facebook Access Tokens when the user may not have access to the FB account?

I am creating a system to allow our clients to create articles and post them in our CMS. The one feature we are being asked to implement is that when an editor publishes an article, that that article gets posted to the company's facebook wall as well.
The tricky part to this is that the people who are allowed to publish articles may not have login credentials to the company's overall FB account. This means that I can't rely on the normal process to retrieve access tokens for accounts (or so it seems).
I did quite a bit of research and came up with the following documentation sources:
http://developers.facebook.com/docs/howtos/login/extending-tokens/
http://developers.facebook.com/docs/howtos/login/server-side-login/
http://developers.facebook.com/docs/concepts/login/login-architecture/
http://developers.facebook.com/roadmap/offline-access-removal/
From these it seems that in order to allow locally authorized users to post to the company's facebook wall I must:
Have a user with valid FB credentials log into an Admin page
Click a button to start the authorization process
Retrieve the short term access token from the FB response and exchange it for a long-lived 60 day token
Store the 60 day token in our database
Each time a user attempts to publish an article, test if the token has expired and if so alert the admin they need to re-authorize.
Is this the only workflow to accomplish this or is there a simpler method, preferably one that does not require the last step.
Use a page token. Get it using a long-lived user access token – then the page token will not expire by default.

Can I publish to pages with an app access_token

As mentioned in this other question, if a user grants the publish_stream permission, I can publish to that user's wall using an app access_token. I tested that and it works. But I couldn't publish to the user's pages using the app access_token! Am I missing something?
Right now I use the /me/accounts/ connection to get the access_token of the pages, and use that to publish. But this is a huge headache for me and for users because these tokens expire often (when users change their password, ...et), and every time that happens the publish fails and I need to email the user to come login again so I can retrieve a new access_token for the page. It's a bad user experience and I'm trying to find a way around it. The app token works for publishing to users, which is great, but I couldn't find a way to make it work for pages. Any tips?
Edit:
To clarify further, I currently request the manage_pages and offline_access permissions, and then fetch the access_token of each page and use that to publish to it. That works. The main problem is that tokens expire, even with the offline_access permission. The most common reason a token would expire is if the user changes her password. Here is a common error that I get a lot when publishing to Facebook pages.
Facebook error. type: OAuthException, message: 'Error validating
access token: Session does not match current stored session. This may
be because the user changed the password since the time the session
was created or Facebook has changed the session for security reasons.'
To handle this, I email the user and ask them to visit our app again, and when they do I grab a fresh set of access_token to work with. But that's problematic because users are confused about why the error happened and blame us for it, and some users don't open their emails so the problem doesn't get solved and then they're angry later when they discover that our app had stopped weeks ago without them asking it to stop.
That's why I was hoping that I can publish with the app access_token to avoid these problems. Since it works for user profiles, I hoped it would work for pages as well. But so far no luck, unless I'm missing something obvious.
What you're describing used to work - all last year we were able to successfully post to fan page walls using the app access token. In fact, for some of our users, I see it still working. However, I think the other two answers are correct, this is no longer the way to post to pages (see "Page Login" here)
That said, you should be able to store the access token of the page to spare yourself the step of re-querying the users' linked accounts.
Unfortunately, the page's access token will suffer the same fragility as a user's, per the answer here: Facebook Page Access Tokens - Do these expire? . The page access token will expire when the user who gave you that access token changes their password.
To publish to pages, there is an extra step where you use their token to get a list of their pages. Each page has its own token, use that token to post to the page. Keep in mind that when setting up the original token, you need to specify that you need access to pages.
my app does exactly what you're after.
I request both manage_pages and offline_access permissions from a user.
I store the user's access_token.
I ask the user which page (determined by me/accounts) they want a stream item posted to and when.
Later, when it is time to publish to a page's feed, I grab the user's access_token from the database, the pageid, and the message.
Using that user's access token, I query the me/accounts and grab the latest access token for that account (aka page)
Using that page's access token, I me/feed (or is it me/posts...away from my codebase at the moment) post the stream item.

Do Facebook Oauth 2.0 Access Tokens Expire?

I am playing around with the Oauth 2.0 authorization in Facebook and was wondering if the access tokens Facebook passes out ever expire. If so, is there a way to request a long-life access token?
After digging around a bit, i found this. It seems to be the answer:
Updated (11/April/2018)
The token will expire after about 60 days.
The token will be refreshed once per day, for up to 90 days, when the person using your app makes a request to Facebook's servers.
All access tokens need to be renewed every 90 days with the consent of the person using your app.
Facebook change announce (10/04/2018)
Facebook updated token expiration page (10/04/2018)
offline_access:
Enables your application to perform authorized requests on behalf of the user at any time. By default, most access tokens expire after a short time period to ensure applications only make requests on behalf of the user when the are actively using the application. This permission makes the access token returned by our OAuth endpoint long-lived.
Its a permission value requested.
http://developers.facebook.com/docs/authentication/permissions
UPDATE
offline_access permission has been removed a while ago.
https://developers.facebook.com/docs/roadmap/completed-changes/offline-access-removal/
Try this may be it will help full for you
https://graph.facebook.com/oauth/authorize?
client_id=127605460617602&
scope=offline_access,read_stream,user_photos,user_videos,publish_stream&
redirect_uri=http://www.example.com/
To get lifetime Access Token you have to use scope=offline_access
Meaning of scope=offline_access is that :-
Enables your application to perform authorized requests on behalf of
the user at any time. By default, most access tokens expire after a
short time period to ensure applications only make requests on behalf
of the user when the are actively using the application. This
permission makes the access token returned by our OAuth endpoint
long-lived.
But according to facebook future upgradation the offline_acees functionality will be deprecated for forever from the 3rd October, 2012.
and the user will be given 60 days long-lived access token and before expiration of the access token Facebook will notify or you can get your custom notification functionality fetching the expiration value from the Facebook Api..
Note that Facebook is now deprecating the offline_access permission in favor of tokens for which you can request an "upgrade" to the expiry. I'm just now dealing with this, myself, so I don't have much more to say, but this doc may help:
https://developers.facebook.com/docs/offline-access-deprecation/
I came here with the same question as the OP, but the answers suggesting the use of offline_access are raising red flags for me.
Security-wise, getting offline access to a user's Facebook account is qualitatively different and far more powerful than just using Facebook for single sign on, and should not be used lightly (unless you really need it). When a user grants this permission, "the application" can examine the user's account from anywhere at any time. I put "the application" in quotes because it's actually any tool that has the credentials -- you could script up a whole suite of tools that have nothing to do with the web server that can access whatever info the user has agreed to share to those credentials.
I would not use this feature to work around a short token lifetime; that's not its intended purpose. Indeed, token lifetime itself is a security feature. I'm still looking for details about the proper usage of these tokens (Can I persist them? How do/should I secure them? Does Facebook embed the OAuth 2.0 "refresh token" inside the main one? If not, where is it and/or how do I refresh?), but I'm pretty sure offline_access isn't the right way.
Yes, they do expire. There is an 'expires' value that is passed along with the 'access_token', and from what I can tell it's about 2 hours. I've been searching, but I don't see a way to request a longer expiration time.
since i had the same problem - see the excellent post on this topic from ben biddington, who clarified all this issues with the wrong token and the right type to send for the requests.
http://benbiddington.wordpress.com/2010/04/23/facebook-graph-api-getting-access-tokens/
You can always refresh the user's access token every time the user logs into your site through facebook.
The offline access can't guarantee you get a life-long time access token, the access token changes whenever the user revoke you application access or the user changes his/her password.
Quoted from facebook http://developers.facebook.com/docs/authentication/
Note: If the application has not requested offline_access permission, the access token is time-bounded. Time-bounded access token also get invalidated when the user logs out of Facebook. If the application has obtained offline_access permission from the user, the access token does not have an expiry. However it gets invalidated whenever the user changes his/her password.
Assume you store the user's facebook uid and access token in a users table in your database,every time the user clicks on the "Login with facebook" button, you check the login statususing facebook Javascript API, and then examine the connection status from the response,if the user has connected to your site, you can then update the access token in the table.
Hit this to exchange a short living access token for a long living/non expiring(pages) one:
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
log into facebook account and edit your application settings(account -> application setting ->additional permission of the application which use your account). uncheck the permission (Access my data when I'm not using the application(offline_access)). Then face will book issue a new token when you log in to the application.
Basic the facebook token expires about in a hour. But you can using 'exchange' token to get a long-lived token
https://developers.facebook.com/docs/facebook-login/access-tokens
GET /oauth/access_token?
grant_type=fb_exchange_token&
client_id={app-id}&
client_secret={app-secret}&
fb_exchange_token={short-lived-token}
This is a fair few years later, but the Facebook Graph API Explorer now has a little info symbol next to the access token that allows you to access the access token tool app, and extend the API token for a couple of months. Might be helpful during development.
check the following things when you interact with facebook graph api.
1) Application connect URL should be the base of your "redirect_uri"
connect URL:- www.x-minds.org/fb/connect/
redirect_uri - www.x-minds.org/fb/connect/redirect
2) Your "redirect_uri" should be same in the both case (when you request for a verification code and request for an access_token)
redirect_uri - www.x-minds.org/fb/connect/redirect
3) you should encode the the argument when you request for an access_token
4) shouldn't pass the argument (type=client_cred) when you request for an access_token. the authorization server will issue a token without session part. we can't use this token with "me" alias in graph api. This token will have length of (40) but a token with session part will have a length of(81).
An access token without session part will work with some cases
eg: -https://graph.facebook.com/?access_token=116122545078207|EyWJJYqrdgQgV1bfueck320z7MM.
But Graph API with "me" alias will work with only token with session part.
I don't know when exactly the tokens expire, but they do, otherwise there wouldn't be an option to give offline permissions.
Anyway, sometimes requiring the user to give offline permissions is an overkill. Depending on your needs, maybe it's enough that the token remains valid as long as the website is opened in the user's browser. For this there may be a simpler solution - relogging the user in periodically using an iframe: facebook auto re-login from cookie php
Worked for me...