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

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/

Related

Post on Facebook pages via Graph API with Facebook4j

I want to create a tool wich allow a user to post his planning on several media at once : he has to fill a form with his establishment week planning, then I post it via newsletter, on his facebook and on his website.
I am struggling with the facebook part. I created an app and made the page subscribe to this app then I tried to use Facebook4j to post something on the page but I am not even able to get the page.
Here is my code :
Facebook facebook = new FacebookFactory().getInstance();
facebook.setOAuthAppId("{app_id}", "{app_secret}");
facebook.setOAuthPermissions("public_profile, manage_pages, publish_pages, publish_actions");
facebook.setOAuthAccessToken(new AccessToken("app_id|app_secret", null));
try {
ResponseList<Account> accounts = facebook.getAccounts();
} catch (FacebookException e) {
e.printStackTrace();
}
which always return me the error :
An active access token must be used to query information about the current user.
How can I have an active access token in order to post on pages which suscribed to my app?
NB : I am not sure I actually need an app. If there is an other way to post on multiple pages without asking for logging each time, I am ok with that too. (some kind of permanent page token maybe?)
Thanks!
Okay first, yes you need an app to perform these requests.
To get what you describe you are requesting the permissions needed correctly, you still miss one - namely pages_show_list.
In addition you have to set the OAuthAccessToken to the users token not to the app token.

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.....

Android Facebook SDK Invalid access token after authorization

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.

Oauth : Where to get userId for AuthorizationCodeFlow . createAndStoreCredential?

I work on google app project and I am struggling a bit with java oauth library (1.10.1-beta).
I followed closely : http://code.google.com/p/google-oauth-java-client/wiki/OAuth2#Authorization_code_flow
Problem is that I dont know from where I should get userId or userEmail. I know there is userinfo API but I am actually trying to create Credentials, so I cannot access userinfo API AFIAK.
My application work nicely on localhost (because of test#example.com user is always there) but fails miserably when deployed in google engine environment (NullPointerException user.getUserId()).
// we ask for token because we got authCode
GoogleTokenResponse gTokenResponse = userUtils.getFlow().newTokenRequest(authCode).setRedirectUri(userUtils.getRedirectUri()).execute();
//trying to search for user email / id / whatever
User user = UserServiceFactory.getUserService().getCurrentUser();
//user is null -> nullPointerException is thrown
userUtils.getFlow().createAndStoreCredential(gTokenResponse, user.getUserId());
Could you please point out a flaw in my use-case or give me a hint ? I searched a lot in SDK samples,Stackoverflow and here but there is not many implementations.
PS: In method AuthorizationCodeFlow.createAndStoreCredential(...) is userId mandatory only when you use persistent storage for Credentials and yes i am using that so userId cannot be null in my case.
Thanks.
You are doing OAUTH (authorization) before you identified your user (authentication). You must redirect your user to the login page when he is not logged in :
UserServiceFactory.getUserService().getCurrentUser() == null
You do that by redirecting the user to the loginUrl :
String loginUrl = userService.createLoginURL(request.getOriginalRef().toString());
The next time the user arrives at your app, he will be logged in, and you can ask for the userId.

Categories

Resources