Android Facebook SDK Invalid access token after authorization - java

I'm trying to get friend list of users in my Android app. To do so I'm using:facebook-android-sdk-3.0.1.
The SDK comes with it's own loging/logout button so I used it. When I click login it handles the event(calls login screen asks for permission) so I have nothing to do. Right after login, onSessionStateChange function being called which is inside the A_class extends Fragment
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
if (state.isOpened()) { // Session open
getFriends(); // Call FQL codes...
} else if (state.isClosed()) { // Session closed
// After first login, It always coming here.Couse:Invalid access token.
}
}
I've followed the tutorials. I was able to: login > ask basic permissions > fetch the friend list(by using FQL) > logout.
After the first successfull login and authentication, If I Logout/Exit from the app, I'm not able to login again. In SDK's finishAuthorization it returns Invalid access token exception, which fails the session to open.
If I login my facebook account on browser and deauthorize the facebook application on my account, I'm able to login again and fetch friends. It looks like I have to refresh the access token or something... Thank you for any suggestions.
I've figguredout that the token is returning empty string "".

Do you try to re-authorize after logout ? Maybe the token expires. In my apps, I dont do a logout. The token is valid, till it expires. So in that case I login again :).

I can't say what the fix is to your exact issue but I remember having a similar problem with FB where the token existed but was invalid.
Basically what happens in the sdk, if I remember correctly, is this
FB auth -> have token? -> yes -> create session with token
As you can see in the above there is no step to check if the token is valid so it's always returning a session that has been closed.
You should try to forcefully flush the token from memory on logout thus avoiding the FB sdk giving you a Session with an invalid token.
The above is just a guess so take it with a pinch of salt.

First check the availability of your access token from Facebook debug tool from Here https://developers.facebook.com/tools/debug/access_token. This tool will provide you with some info about the access token provided like Time to Expire and Scopes ... etc
If the token is expired you have to refresh it (re-authorize it) using the graph api:
https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id=app-id&client_secret=app-secret&fb_exchange_token=old_token
Just replace old_token in the URL with the expired access token and use your app_id and secret instead of client_id and client_secret respectively. The return value is a new token that you can use instead of the old one.
You can refresh the access token at the time you got the exception of invalid access token and replace it before logging in.

Related

Facebook - How to Pragmatically post to facebook page? | Refreshing Access Token

So I have been stuck on this for a while, I'm trying to post from my web application (Spring boot) AUTOMATICALLY without any user interaction, NO POPUP LOGIN VIA FB OR AUTHORIZE FB ACTION nothing.
My application itself should do this. I achieved this by using :
public String postStatusOnPage(String message) {
if (socialFacebookConfiguration.isEnableWorkaroundAutoPost()) {
String id = facebook.pageOperations().post(new PagePostData(socialFacebookConfiguration.getPageId()).message(message));
log.log(Level.INFO, "Created New post id: " + id);
return id;
} else {
return null;
}
}
This works all ok. Bud , there is an issue and i dont know if my solution is really a right way to do it.
Im getting facebook The authentication has expired.
My access token that i have defined in application.properties
workaround.social.facebook.accessToken=...
Will expire. I dont know about how to refresh it. I have cheated a bit by using
https://developers.facebook.com/tools/explorer/
Question :
So How do I automatically get new access token? Is this a correct way of doing this OR is there better way? Is there a possibility to have access token that never expires?
Side note : MY application has OAuth2 login via google, bud I want application itself to do this, without any user being logged in(administrator as a human).
There is another token that i have , its app token
Bud this one does not work for posting to my page. On invocation throws :
faceboook An active access token must be used to query information
about the current user.
An App Token does not have any relation to a User or Page. You MUST use a Page Token to post to your Page, and you can use an Extended Page Token for that.
More information about Tokens: https://developers.facebook.com/docs/facebook-login/access-tokens/

How to get access token using refresh token?

In my app we want to provide login with google. So i went throught the folowing Quickstart and created a sample extending it by setting access_type to offline. So that i can get refresh token as their will be background task that will perform operation on those account after a particular interval of time, example: saving starrred mail in some file on server for each user.
So i need to know:
How to save refresh token ? like save it in DB with userId or somthing or save whole credential object as few post i have seen use credential object
How to use refresh token to get accesstoken ?
When does refresh token expires?
Code reference will be very useful.
Thank you!!
1.You can save the refresh token in DB as like userId, you can get new access token by using the refresh token
2.You need to pass the Client Id, Client Secret and Refresh token to get the new access token
3.Refresh tokens are valid until the user revokes access.

How to auto-authenticate with box.com java sdk

My question is similar to this post:
How to get an access token without Box’s authorization page
In that post, he asks:
I have been granted access(collaborate) in a folder. What I need is to access the folder daily and fetch files from it. Right now the developer token I generate expires in 1 hour. Is there a way I can get the authorization code without the first leg, which requires a user interface. This way I can refresh the access toke whenever I fetch files.
The highest rated answer from "Skippy Ta" tells me most of what I need to know EXCEPT the following:
How do I authenticate using the developer token and how do I refresh? From the github repo for the HelloWorld sample app (https://github.com/box/box-java-sdk-v2) I downloaded, I see these two steps:
boxClient.authenticate(boxOAuthToken);
for the initial authentication, and
boxClient.addOAuthRefreshListener(new OAuthRefreshListener() {
#Override
public void onRefresh(IAuthData newAuthData) {
// TODO: Update the stored access token.
}
});
for the refresh.
I'm having trouble putting all this together. First, the authenticate method does not accept a String boxOAuthToken, it accepts an IAuthData object, whatever that is. So I cannot conduct the initial authentication.
Even if I were to achieve initial authentication, I could not refresh, because I don't know how to access the token once I'm authenticated in order to store it, and if I stored that token as a String, I don't know how to wrap it in the proper object and conduct the update alluded to by the
// TODO: Update the stored access token.
comment above. Thanks for any help you can offer.
You can take a look at the javafx login UI: https://github.com/box/box-java-sdk-v2/tree/master/BoxJavaFxOAuth
But anyway if you need to build a BoxOAuthToken object from access token and refresh token and authenticate from it, here is what you can do:
HashMap<String, String> tokenMap = new HashMap<String, String>();
tokenMap.put("access_token", access);
tokenMap.put("refresh_token", refresh);
BoxOAuthToken token = new BoxOAuthToken(tokenMap);
boxClient.authenticate(token);
As for the refresh, the sdk auto-refreshes. The only time you need to worry about it is when your app quits and you need to persist the auth. At that point you can save the oauth token out. The refresh listener is used to update the oauth token for you so at the point you need to save oauth out, you have the latest oauth data.

Post to Facebook Page wall using RestFB api

I am trying to post on the wall of a facebook page. I am able to post on the user wall using App Access token.
I got the App Access Token through extending the DefaultFacebookClient
public class ConnectionService extends DefaultFacebookClient{
public ConnectionService(String appId, String appSecret) {
AccessToken accessToken = this.obtainAppAccessToken(appId, appSecret);
this.accessToken = accessToken.getAccessToken();
}
}
With this I am able to post to user wall using the appID and appSecret. But when I tried to post to Page Wall
i get error of " The user hasn't authorized the application to perform this action"
Anyone can advice?
To post on a facebook page wall, you will need to follow these steps:
Head over to https://developers.facebook.com/tools/explorer
Click on "Get Access Token"
Under "Extended Permissions" tab, select select manage_pages and publish_actions and hit "Get Access Token"
Now under Graph API, under Get call, type in "me/accounts" and hit Submit
In the screen below, you will see the "data" json object with all your pages and page access tokens.
Grab the desired page token access and replace the PAGE_ACCESS_TOKEN in the code below with this token.
Replace PAGE_NAME with your page name (the page name slug in the URL).
Run the below code and that should do the job :)
final FacebookClient fb = new DefaultFacebookClient(PAGE_ACCESS_TOKEN);
final Page page = facebookClient.fetchObject(PAGE_NAME, Page.class);
facebookClient.publish("PAGE_NAME/feed", FacebookType.class, Parameter.with("message", "RestFB test"));
The App Access Token is the most basic one, and will not allow you to post anything. In order to post something to a Facebook Page (as a Page), you need to get a Page Access Token.
The process is a bit complicated, because you actually need to authorize the user with the "manage_pages" permission first, with the User Access Token you can call the API to get a Page Access Token (/me/accounts).
See those links:
https://developers.facebook.com/docs/facebook-login/
https://developers.facebook.com/docs/facebook-login/access-tokens/
http://www.devils-heaven.com/facebook-access-tokens/
Btw, the REST API is deprecated: https://developers.facebook.com/blog/post/616/
You can also try the "Client Token" (Developer Settings > Advanced), i never worked with that one but it could be the easiest solution. In any case, an App Access Token is the wrong one.
Make sure that the scopes you mentioned while authenticating user includes manage_pages also. This error occurs when you have not included this in your scope. Refer this
Since u r generating access token from java class. u can set the permissions u require from user in ur manage app link from ur facebook profile page and get the access token here.....

Why Facebook Access Token Changed Each and Every Access?

We are using restFB 1.6.12. I am getting the facebook access token in two ways,
1. CLIENT_APP_ID = "XXXXXXXXXXXXXXXXXX";
CLIENT_SECRET = "XXXXXXXXXXXXXXXXXX";
REDIRECT_URL = "XXXXXXXXXXXXXXXXXX";
AUTH_CODE = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
SCOPE = "email,read_stream";
Redirect to facebook as the example. As a result I'll get an
authorization code
https://www.facebook.com/dialog/oauth?client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&scope=email,read_stream
asking for an access_token using,
https://graph.facebook.com/oauth/access_token?client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&client_secret=YOUR_APP_SECRET&code=THE_CODE_FROM_ABOVE
this returns the access token like this,
access_token=CAAHWfjdHDKcBAIL0zHMeJKzJw8Ug7WrrrkNxpBnK7ubnFR1RGtIIZA7T3UPlhCSV0hPJXZAgTcKfBSfHZAyxsndc3RT72XMREjACxnGb0ZCGMZAUgDWH3FgOhnaoSBMgkaQBPDOCCEKcLnznMYSncWS7dVxl9IFrSzeFjF6LKOWB3NTynl5X1&expires=5125218
2. AccessToken accessToken = new
DefaultFacebookClient().obtainAppAccessToken(appid,appsecret);
String token=accessToken.getAccessToken();
It reurns the access token like this,
access_token=517312558337191|5oHY9T3cZICO_TCeK8OdXKg5Y08
If I use the first(1) one, it works fine for first access after then every access throws an error
Auth Token= {"error":{"message":"This authorization code has been used.","type":"OAuthException","code":100}}
If I use the second(2) one, it works fine only for publicSearchMessages but when I access publicEvents or other searches it throws an error
com.restfb.exception.FacebookOAuthException: Received Facebook error response of type OAuthException: (#200) Must have a valid access_token to access this endpoint
at com.restfb.DefaultFacebookClient$DefaultGraphFacebookExceptionMapper.exceptionForTypeAndMessage(DefaultFacebookClient.java:766)
at com.restfb.DefaultFacebookClient.throwFacebookResponseStatusExceptionIfNecessary(DefaultFacebookClient.java:688)
at com.restfb.DefaultFacebookClient.makeRequestAndProcessResponse(DefaultFacebookClient.java:630)
at com.restfb.DefaultFacebookClient.makeRequest(DefaultFacebookClient.java:592)
at com.restfb.DefaultFacebookClient.makeRequest(DefaultFacebookClient.java:556)
at com.restfb.DefaultFacebookClient.fetchConnection(DefaultFacebookClient.java:219)
My question is, what is the difference between these two access token and how can I programmatically generate access code for first one to works publicSearchMessages, getPublicEvents and other searches?
Which one access token is used to works as expected?
Access_tokens allow users to interact with your apps in secure and social ways. While we are removing the use of the offline_access permission, through a migration setting in the App Dashboard, we are now allowing the option to use access_tokens with a long-lived expiration time that can be renewed each time the user revisits your app
When a user visits your site with an existing, valid, short-lived user access_token, you have the option to extend the expiration time of that access token.
extend the expiration time once per day, so even if a user revisits your site multiple times a day, the token will be extended the first time requested. You must make sure to call the new endpoint below before the short-lived access_token expires.
Using the new endpoint below, you will be able to extend the expiration time of an existing, non-expired, short-lived user access_token.
To get the long-lived user access_token simply pass your own client_id (your app_id), your app_secret, and the non-expired, short-lived access_token to the endpoint. You will be returned a new long-lived user access_token; this access_token will exist in addition to the short-lived access_token that was passed into the endpoint
In short Get a page access token – those don’t expire per default; and make sure to do so with a long-time user access token
You can access facebook doc here for more info
To get an extended Page Access Token, exchange the User Access Token for a long-lived one and then request the Page token. This "extended" token for Pages will actually not have any expiry time.
https://developers.facebook.com/docs/howtos/login/extending-tokens/#step1
resolve this by executing a curl request, and saving "Page access token" in your code manually

Categories

Resources