Creating Facebook event on behalf of a page from Android client - java

I thought it is easy thing to do, but seems that it is not. I have an Android app. User logs in into this App, using Facebook. I also have a Facebook page (besides Facebook app). So, I want to create an event on behalf of my page from my android app. Here is what I do:
Bundle params = new Bundle();
params.putString("name", "name");
params.putString("description", "descr");
params.putString("location", "loc");
params.putString("start_time", "properly_formatted_time");
new Request(
Session.getActiveSession(),
"/" + PAGE_ID + "/events?access_token=" + PAGE_ACCESS_TOKEN,
params,
HttpMethod.POST,
new Request.Callback() {
public void onCompleted(Response response) {
}
).executeAsync();
I have generated long living token with all required permissions as described here: Long-lasting FB access-token for server to pull FB page info
If I try to create event, being logged in as myself (admin of a FB page and application), it works fine.
When I am using someone's account, who is not an admin, I am receiving following error:
{HttpStatus: 500, errorCode: 1373019, errorType: Exception,
errorMessage: You must be an admin of the specified page to perform
the requested action.}
So, how it is possible to fix this. I've googled around and found some similar questions, like How to post to a Facebook Page (how to get page access token + user access token), but those either have no correct answer, or are using "me/account" and then get access_token, which is not something I want to do.
Any help would be greatly appreciated.

There's no other way in my opinion than to get the Page Access Token via the /me/accounts (being logged in as admin of that page), and then store this Token in the app itself.
What I'm not really understanding is that (all) the users can then create an Event for your Page. Is that really what you want?

Related

Google API Authorization Using Scribe OAuth Java Library

I am trying to make a Java class which would call upon Google's API to recreate an access token to a user's account with new permissions/larger scope. This class is to be instantiated by a Java servlet I had created. I want a function within that class to return a new access token. For this class to do that, I am using the Scribe library.
In Scribe's quick guide, there are two steps which concern me and have me stumped:
Step Three: Making the user validate your request token
Let’s help your users authorize your app to do the OAuth calls. For
this you need to redirect them to the following URL:
String authUrl = service.getAuthorizationUrl(requestToken);
After this either the user will get a verifier code (if this is an OOB
request) or you’ll receive a redirect from Twitter with the verifier
and the requestToken on it (if you provided a callbackUrl)
Step Four: Get the access Token
Now that you have (somehow) the verifier, you need to exchange your
requestToken and verifier for an accessToken which is the one used to
sign requests.
Verifier v = new Verifier("verifier you got from the user");
Token accessToken = service.getAccessToken(requestToken, v); // the requestToken you had from step 2
It does not seem to specify how to get that verifier from the user. How am I supposed to do that? How do I redirect my user to the authURL, and how do I get it to send its verifier back to this class of mine, which initiated the request to begin with?
If this is unclear, let me structure the question differently, taking Scribe out of the equation: To get an authorization code from Google (which would be used to then get a refresh token and access token), I would execute the following URL connection from within the servlet (yes, I've tried to answer this problem without the Scribe library, and still can't figure it out):
URL authURL = new URL("https://accounts.google.com/o/oauth2/auth");
HttpsURLConnection authCon = (HttpsURLConnection) authURL.openConnection();
authCon.setRequestMethod("GET");
authCon.setDoOutput(false);
authCon.setConnectTimeout(100000);
authCon.setRequestProperty("response_type", "code");
authCon.setRequestProperty("client_id", CLIENT_ID);
authCon.setRequestProperty("redirect_uri",
"http://**************.com/parseAuth/");
authCon.setRequestProperty("scope", convertToCommaDelimited(scopes));
authCon.setRequestProperty("state", csrfSec);
authCon.setRequestProperty("access_type", "offline");
authCon.setRequestProperty("approval_prompt", "auto");
authCon.setRequestProperty("include_granted_scopes", "true");
What has me stuck is what I should be putting for the redirect URI. After getting the user's approval for the new scope, this authorization URL would return an authorization code to the redirect URI, and seemingly nothing to whatever called it. (Am I correct in this?) So if I have another servlet as the redirect URI to parse/extract the authorization code from the response, how in the world do I get that authorization code back to my first, initial servlet? It seems to me that there is no way to have it give back the value to the servlet, in the same position of the code from which the URL was called. It looks like the function has to end there, and all new action must take place within that new servlet. But if that is the case, and I send that auth code to Google's API which would send back a refresh token and access token to ANOTHER servlet I would make to be its redirect URI, how do I possibly get that information back to what it is which called the initial servlet to begin with? That seems to be the same problem at its core, with the problem I am having with Scribe.
I've been stuck on this for many hours, and can't seem to figure out what it is I am supposed to do. I feel like I am missing some key concept, element, or step. I need this clarified. If it is at all relevant, my servlet is hosted on a Jboss application server on OpenShift.

Google Client Login Handling AuthToken

I have a non-gae, gwt application and it have a module that allows users to create documents online via google docs api.
To do that, i first ask user to enter the name and type of the document, than create a new document via google docs api with the given parameters and onSucces part of that servlet returns edit link which is used in client side to open a new page to edit the created document.
Problem that, eachtime i try to open that editLink user have to enter login informations. To solve this i try to use Google Client Login but i am totally lost i think.
First i have username and password of user and can directly use them, after searching i tried some examples which usually returns a token like this and that. Now what should i do with token? How can it be used to complete login process or should totally find another way to do login? All those oauth1,oauth2 and etc. documentations confused me a little bit.
here are my steps;
Server side;
LinkedHashMap<String, String> hashMap = new LinkedHashMap<String, String>();
// Login
DocumentList docList = new DocumentList("document");
docList.login(ServletUtil.googleDocsLoginInfo().get("username"), ServletUtil.googleDocsLoginInfo().get("password"));
//Create document with a unique suffix
String docName= parameterName+ "-Created-" + new Date();
docList.createNew(docName, dosyaTur);
// Find the created document and store editLink
DocumentListFeed feed = docList.getDocsListFeed("all");
for (final DocumentListEntry entry : feed.getEntries()) {
if (entry.getTitle().getPlainText().equals(docName)) {
hashMap.put("editlink", entry.getDocumentLink().getHref());
}
}
return hashMap;
And Client side;
#Override
public void onSuccess(LinkedHashMap<String, String> result) {
String editLink = result.get("editlink");
Window.open(editLink,"newwindow","locationno");
}
Thanks for your helps.
If I may suggest using OAuth instead of Client Login, which is outdated and less secure.
The functionality is basically the same (for OAuth 2.0 there are more ways to handle the login).
I know, trying to understand how to access the api via OAuth is very confusing, so I try to break it down a little:
If you use OAuth 2.0 you may want to use a library like this one or you can try out my own (although I wrote it for Android, this could work with other Java Apps including Web Apps)
This is what happens when a user logs in the first time with your app:
> Your App sends an authorization request containing some information about your app - for example your app needs to be registered with google and therefore has a special application key
< The Server sends you a url, open it in a new browser window and let the user login. There he will be asked to allow your app to access his account (or some parts of it) - when he confirms he will be prompted an Authorization Code which he needs to copy
> The user gets back to your app, where you will ask him for the authorization code. After he gave it, your app connects again with the server and sends the code as some kind of authorization grant of the user.
< The Server answers with a access token
All you need to do is use this access token (also called a bearer token) in all your requests to the server hidden in the header message.
I am sorry I can't give you a more precise answer right now, since I never used GWT. All I can say is, try using OAuth2, it is actually very simple (after you learn what all this confusing things like authorization flow, bearer token etc are) and really comfortable for your user, once the he has done the first login.

Play Framework appending #_=_ to redirect after Facebook auth via OAuth2?

I'm doing a simple redirect after calling OAuth2::retrieveAccessToken() with Play Framework. I'm having funny characters appended to the URL that I never put there, so the end result looks as follows:
http://localhost:9000/#_=_
Where on earth does the #_=_ come from? Here's my route definition from the routes file:
GET / Application.index
Here's the code snippet of the controller dealing with the Facebook authentication:
public static void facebookConnect() {
OAuth2 facebook = new OAuth2(
"https://graph.facebook.com/oauth/authorize",
"https://graph.facebook.com/oauth/access_token",
"2#############6",
"c##############################2"
);
if(OAuth2.isCodeResponse()) {
OAuth2.Response oauthResponse = facebook.retrieveAccessToken(facebookAuthUrl());
if(oauthResponse.error == null) {
//... Somewhere here, something is causing #_=_ to be appended to the URL?
Application.index();
}
}
facebook.retrieveVerificationCode(facebookAuthUrl());
}
EDIT:
According to this page, Facebook changed their API recently to include the = if request_uri is empty, the problem is...my request_uri has been explicitly set?
This was added after a security update.
From the Facebook developer blog:
Change in Session Redirect Behavior
This week, we started adding a fragment #_=_ to the redirect_uri
when this field is left blank. Please ensure that your app can handle
this behavior.
Maybe these characters come from the facebook callback. I was getting a FB callback like
localhost:9000?someparams#code=verylongcodefromfacebook
I could get rid of the # just by sanitizing the params before requesting the access token.

how to get access token using gdata in java

I am developing a Java Application where I am implementing 3-legged OAuth using google gdata in Java. This application is registered on Google App Engine. At the first stage, I am getting the unauthorized request-token successfully. I am storing that token in session and create a link using createUserAuthorizationUrl(oauthParameters). Then on clicking the link, it redirect me to "Grant Access Page".
Now, even though I grant access, it doesn't show me this page. But, it redirects me to my callback url. However, this seems proper. But, it also doesn't add the entry under My Account. Here, I am storing the oauth_token in session.
When getting redirected, the url of that page contains oauth_token & oauth_verifier, both ! Now, on this callback url, I have a submit button & set action of for to an accessTokenServlet.java. The code of this servlet is as follow :
Now I am sending request to fetch Access Token. My code is :
GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
oauthParameters.setOAuthConsumerKey(CONSUMER_KEY);
oauthParameters.setOAuthConsumerSecret(CONSUMER_SECRET);
oauthParameters.setOAuthType(OAuthParameters.OAuthType.THREE_LEGGED_OAUTH);
GoogleOAuthHelper oauthHelper = new GoogleOAuthHelper(new OAuthHmacSha1Signer());
oauthParameters.setOAuthToken(request.getSession().getAttribute("oauth_token").toString());
oauthParameters.setOAuthTokenSecret(request.getSession().getAttribute("oauth_token_secret").toString());
try {
String accessToken = oauthHelper.getAccessToken(oauthParameters);
out.println("Access Token : " + accessToken);
} catch (OAuthException e) {
//System.out.print("Response Status : " + response.getStatus());
out.println("Exception : ");
e.printStackTrace();
return;
}
While clicking on submit button, it prints "Access Token : " & nothing ! No token returns !
I am getting wrong at the stage of authorizing the request token itself. But, I am not getting, what problem got generated ?
The page with the verifier you linked to should only happen if you pass in an oauth_callback of oob — this indicates that you will be moving the verifier out-of-band. I strongly recommend against using oob for anything but debugging. Instead, you should be setting a callback URL and getting the verifier out of the query string.
In the code above, I don't see anything that sets the verifier in the OAuth parameters, so that's likely your problem. You're also not doing much in the way of error handling, and that's a really important piece of the OAuth flow — for example, once you've got it working, try canceling the OAuth process and see how your application handles it.
You will only see the entry in your issued tokens list after you've fully completed the process and obtained an upgraded access token.

Invalid parameter exception on client.auth_getSession() in Facebook java API

I want to connect to a my facebook application using the facebook java api 2.1.1(http://code.google.com/p/facebook-java-api/). My application is in "Desktop" mode so I should be able to access it outside of a web application. I have not defined any callback url for it as well. My code looks something like this.
FacebookJsonRestClient client = new FacebookJsonRestClient( FB_APP_API_KEY, FB_APP_SECRET );
String token = client.auth_createToken();
HttpClient http = new HttpClient();
http.setParams(new HttpClientParams());
http.setState(new HttpState());
final String LOGIN = "https://login.facebook.com/login.php";
GetMethod get = new GetMethod(LOGIN + "?api_key=" + FB_APP_API_KEY + "&v=1.0&auth_token=" + token );
http.executeMethod(get);
PostMethod post = new PostMethod(LOGIN);
post.addParameter(new NameValuePair("api_key", FB_APP_API_KEY));
post.addParameter(new NameValuePair("v", "1.0"));
post.addParameter(new NameValuePair("auth_token", token));
post.addParameter(new NameValuePair("email", "my-email"));
post.addParameter(new NameValuePair("pass", "my-password"));
http.executeMethod(post);
String session = client.auth_getSession(token);
However instead of returning the session the API throws an exception:
com.google.code.facebookapi.FacebookException: Invalid parameter
at com.google.code.facebookapi.FacebookJsonRestClient.parseCallResult(FacebookJsonRestClient.java:354)
at com.google.code.facebookapi.ExtensibleClient.callMethod(ExtensibleClient.java:535)
at com.google.code.facebookapi.ExtensibleClient.callMethod(ExtensibleClient.java:472)
at com.google.code.facebookapi.FacebookJsonRestClient.auth_getSession(FacebookJsonRestClient.java:278)
Can anyone please tell me whats wrong with this code? And what is the correct way to access a facebook application in desktop mode using the java api (v. 2.1.1).
Thanks for your help.
Regards
Nabeel Mukhtar
As far as I understand FB's API, you're not supposed to provide username and password manually but instead let the user input them manually and then allow the Facebook Login to redirect the user back to your application. This means that instead of providing "email" and "pass" you provide "next" and "cancel" URL:s instead.
This is purely a security feature of FB API and while the theory behind it is alright, the execution is far from optimal.
See this discussion thread on the Google Code site. There's a link in the that thread to a wiki page which explains how to do desktop auth.

Categories