Facebook Unity SDK - Deauthorizing account in Facebook settings throws no issue on login - facebook

What is specifically supposed to happen when a token is expired or the access code is no longer valid?
I check first to ensure we are logged in. If we are, I get the access code:
AccessToken.CurrentAccessToken.TokenString
When I deauthorize the token via the Facebook account settings, what should I be seeing in terms of issues here? The token still exists, the date has not yet still been reached. I am currently only using this for account linking with an external backend. Do I have to actually send an API query and handle an error or is there another way to ensure the AccessToken is still valid?

You could try and debug the token, https://developers.facebook.com/docs/facebook-login/access-tokens/debugging-and-error-handling - but since this needs either an app access token or a user token of the app admin as additional parameter, this should only be done in server-side code.
Plus, if you make API calls to debug tokens all the time, it will slow your app down for anyone who’s token is still perfectly fine as well. So trying to make your regular API call, and react if that fails due to an expired token, might be the better alternative.
To “validate” a token with minimal overhead, you can just make a /me?fields=id request, then you will just get the app-scoped user id back if the token is valid, or an error otherwise.

Related

How can I get a permanent access token to post to a Facebook page that I own?

I am the administrator of a Facebook Page. I am building a web app which, under certain circumstances, will post on Facebook as that Page.
With most APIs, I would just get an API key, and supply that when connecting to the API from my app. But Facebook expects an access token instead of an API key. (Specifically, in this case, it needs a "page access token".)
I am trying to figure out how to get a page access token that will be as permanent as possible.
After jumping through a bunch of esoteric, undocumented hoops (see here and here) in order to get a token that wouldn't expire, I had this working. When I ran the token through Facebook's Access Token Debugger, the "Expires" field read "Never". All was good in the world.
But, the next day, my token became invalid anyway. The Access Token Debugger, and my app's calls to Facebook's PHP SDK, both started returning this error:
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.
It seems that a token can become invalid for a variety of reasons (but this article is five years old, so who knows – Facebook changes things every two weeks). I had not changed my password. (I might have logged out of Facebook, though.) Facebook offers no specifics about why this particular token might have become invalid.
I've also seen a few references to a permission called offline_access, but Facebook seems to have removed this.
I suppose my question is twofold:
In general, I've found Facebook token authentication to be incredibly brittle when calling the Facebook API from the server. The token system seems to be designed mainly to allow other users to grant (or revoke) various kinds of account access to my apps. But that's not what I'm doing – I'm trying to get a token that will let me post to a page that I own. And for that scenario, Facebook's aggressive invalidation of tokens becomes a serious liability. I can't launch my app if my access token (and therefore my Facebook integration) could randomly stop working at any moment, requiring me to generate a new token and update the app. This seems absurd. Is there an alternative method of authenticating to Facebook for my purposes?
If a page access token is, in fact, the best way to authenticate my app to Facebook in order to post as my Page: how can I ensure that my token doesn't spontaneously become invalid?
I hate developing for Facebook :/ Thanks for any insight you can offer.
Extended Page Tokens are valid forever. They only get invalidated if you change your password or if you change the App Secret of your App. There´s really no magic in it, checking if the Token is still valid is obviously not a bad idea but that´s up to you. For example, you can send yourself an automated Email when there is an error using the Token, so you can refresh it. But it will really just happen if you change your password.
Links:
https://developers.facebook.com/docs/facebook-login/access-tokens
http://www.devils-heaven.com/facebook-access-tokens/

Facebook Access Token is Expired using Facebook SDK PHP

I am trying to link my application to a facebook user account but every time I go through the process of retrieving their profile I get this error:
string(140) "{
"error":{
"message":"An active access token must be used to query information about the current user.",
"type":"OAuthException",
"code":2500
}
}"
The reason I am confused is that when I initially request an access_token from facebook it return a token for me.
string(56) "access_token={app_id}|{app_secret}"
Which I am then told is expired and I don't know why.....
I understand in order to get an access token you must follow a particular workflow.
Client Requests access and permissions via SDK and Login Dialog.
User Authenticates and approves permissions
Access token returned to client
Graph API calls with short-term access token (web) or long-term access token (native mobile)
Based on what I've seen in my code, I get to step 3 but step 4 fails because the token is said to be expired. Does anyone have any idea what I can do to fix this!?
I notice that for step 1 the login dialog is never shown but I still get an access code returned despite this. Could that be something to do with it? This is the way I perform step 1.
<a class="lists" href="https://graph.facebook.com/oauth/authorize?client_id=564083793722908&redirect_uri=<?=urlencode($facebook_callback_url)?>&scope=offline_access,publish_stream,status_update">Connect a Facebook account</a>
Step 2. never seems to occur
Step 3. An access token is returned though. See above.
Step 4. Fails with the above error of expiration.
Any advice?
You cannot request user information with an app access token. You need a usser access token to do that. Your Login process needs to adhere the docs at
https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow/v2.1#login
to get a user access token. Apparantly, this is not the case with your code.
Furthermore, you're only using permissions which are (long) deprecated. See
https://developers.facebook.com/docs/facebook-login/permissions/v2.1#adding
https://developers.facebook.com/docs/facebook-login/permissions/v2.1#reference

Does a Facebook application's access token expire?

This is the access token associated with my Facebook application -- the thing that comes back from https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id=APP_ID&client_secret=APP_SECRET. Can I get this once from FB and save it away somewhere for future use, or do I need to refresh it on a regular basis?
Access Token Tool - Facebook Developers
App tokens do not expire and should be kept secret as they are related to your app secret.
I don't know for sure, but since the documentation does not state that you get back an expiration time for the access token, I guess that it's an educated guess that it does not expire.
But why does it matter? the application authentication process is much simpler than the one with users, so just save the token somewhere (db, memory) and then try an api call, if it fails just issue one call to obtain a new token, save that, and continue as usual.
If you want a token to manage a page, never-expiring token can be obtained by
Get user token
Exchange user token to long-living token (Valid for 30days)
Obtain a page token with this user token (This page token is not going to expire)
When you check the token you've got, check it on Debugger. You will now see 'Expires Never'.
Documentation is on Facebook Developers ,Scenario 5: Page Access Tokens
My app access token does not seem to have changed for just under a month. I do not know if it changes. For fun I just changed my app secret...
My app access token then immediately changed and when I try to use the old one I get a
HTTP 400 error with a message body...
{"error":{"message":"Invalid OAuth access token signature.","type":"OAuthException","code":190}}
My advice is save the access token and use it. Unless you get the message above in which case obtain a new one and use that. One thing that I have not checked yet is if you get the same result if the user access token (that you may be querying) has expired instead.
For each and every user token (which is what you're getting from your link), there is an expiration date. Take one of those tokens to https://developers.facebook.com/tools/debug and debug it. You will see that generally they expire within 60 minutes or so.
To extend that user token, call the exchange command (https://developers.facebook.com/docs/offline-access-deprecation/) to get it to become a 60 day token. That user token has to be still valid (not expired) to do this.

Facebook access token invalid with message "session does not match current stored session"?

I have recently started getting this error while posting to facebook newsfeed stream
of an app user,
I do have an offline access permission for the access tokens, and they worked
fine previously.
This error is coming for 30-40% of the users.
"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 may be due to a system error."
It's possible for your access token to become invalid for a variety of reasons (expiry time passed, user changed password, user deauthorized your app, user logged out of Facebook, etc.). You should always design to account for this scenario.
If your users are active, it's easy to get a new access token from the OAuth endpoint without them having to do/see anything. If not, you should make a plan (such as emailing them) for how you will get them to return so you can get a new access token. The scenario you're describing is not necessarily unusual. You can find some code samples here for help on how to handle expired access tokens.
This is undocumented but I just tested it and it works with expired access tokens. Should work on access tokens that have been invalided if you know their user id, and they haven't revoked privileges to your app. First, you can verify that you still have have the permissions you need by calling using this url:
https://graph.facebook.com/userID/permissions?access_token=appID|appSecret
If you still have publish_stream permissions, you can issue a HTTP POST to this url:
https://graph.facebook.com/userID/feed
with post parameters of access_token=appID|appSecret&message=test message
There seem to be a lot of questions about why your token would have expired so quickly. I think I can shed some light on that. Here are a number of scenarios I have found which cause this:
There is the obvious one; the user changed his password. There is nothing you can do about this. They will need to reauthorize your app. The rest of these scenarios deal with page tokens, which are similar to a token for a user profile, except they come from querying /me/accounts with the user token of a valid administrator for the page. These seem to expire much more frequently.
It seems that if ANY administrator of a page changes their password (not necessarily the one who's token you are using), this can cause the token to expire. Also, if you have some pages in your system with the same administrator, calling /me/accounts often refreshes ALL of the tokens for the pages this user administrates. That means if you are connecting a new page for a user with existing pages, you will need to update the existing page tokens with the new ones provided by /me/accounts.
Finally, the way I deal with this in my system is to store the admin user and token as a parent of the page token in my database. This way when I need to reconnect a page or add a new page, the system can lookup and update any related page tokens received from /me/accounts. It also allows you to automatically attempt to refresh the token by calling /me/accounts when you receive the expired token exception.
Hope some of this helps!
Check out the blog post officially from facebook: How-To: Handle expired access tokens
The offline session token is changed whenever a user changes his password. If a previously working session suddenly stops (and you're getting that error) then the user's password was changed (probably by the user) and you will need to re-prompt them to grant you offline access and save the new session token you get.
I also faced this issue while accessing the post comments from my command utility. In my case everything was working fine, until suddenly I got the error:
The remote server returned an error: (400) Bad Request.
After diagnosing the problem, I found that the Facebook access token is expiring after a period of time even though I created it with the offline_access option as below:
https://www.facebook.com/dialog/oauth?client_id=[APPID]&redirect_uri=[URL]&scope=user_photos,email,user_birthday,user_online_presence,offline_access
After wasting of lots of time on RND, I found that there is an option in the app's Advanced Settings for Remove offline_access permission. My client had enabled it, and that's the reason my token was expiring. Have look at the image below:
In my case I had to generate a new page access token because I changed my Facebook password.
You can do that by going to https://developers.facebook.com, click on your app, see the menu on the left, choose Messenger, then Settings, then scroll to Access Tokens, click Generate token, copy the token and paste it into your configuration file.

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.