Getting a user access token in facebook using Koala - facebook

I am writing a simple procedure that automatically makes a facebook
post. From what I understand, I need to have a "user access token" to
do this. I am using Koala (but the philosophy is similar for other
libraries). Anyway, I create a new OAuth account:
#oauth = Koala::Facebook::OAuth.new(app_id, app_secret, callback_url)
The koala instructions then become somewhat unclear. The next two lines are:
#oauth.url_for_oauth_code # generate authenticating URL
#oauth.get_access_token(code) # fetch the access token once you have the code
Where does the "code" variable come from? It doesn't say in the
documentation. Also, does the "get_access_token" method get an "app
access token" or a "user_access_token"? The method name is not clear.
I tried going to the url that the [url_for_oauth_code] method gave me,
but it gives me no code! Where does the "code" variable come from?

On the front page of Koala it states you need to go through the OAuth process described at http://developers.facebook.com/docs/authentication/ (this is an old link but the content within is valid)
Specifically
#oauth.url_for_oauth_code
https://github.com/arsduo/koala/blob/master/lib/koala/oauth.rb#L85
Generates a URL that you need to direct the user to based on the repo it's something like
https://www.facebook.com/dialog/oauth?
client_id={app-id}&
redirect_uri={redirect-uri}&
scope=email
Based on the documentation https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow/v2.2#login, when the response_type is omitted the default response type is code. So the above is equivalent to
https://www.facebook.com/dialog/oauth?
client_id={app-id}&
response_type=code&
redirect_uri={redirect-uri}&
scope=email
So on redirect to redirect-uri, this URL will be appended with the code param which you must handle then supply to
#oauth.get_access_token(code)
The access token is a user access token.

Related

Facebook graph api - Unsupported get request

I'm creating a custom module in Drupal, that for part of its functionality must fetch posts from a business page. So for simplicity, I'm using fbapp module as a dependency (drupal.org/project/fbapp), so that I can use it's authentication and request functions (fbapp_app_authenticate() and fbapp_graph_request()) without having to worry about the constant facebook graph updates making my own code obsolete.
I've created a facebook app, so authentication should be app token, using appid and app secret. This seems fine and I'm getting back access_token. However, when I try to read posts from a publicly available page (the clients), I get the response:
"Unsupported get request. Please read the Graph API documentation at https:\/\/developers.facebook.com\/docs\/graph-api"
Here's the queries and responses my code produces:
graph.facebook.com/oauth/access_token?client_id=<redacted>&client_secret=<redacted>&grant_type=client_credentials
array(1) {
["access_token"]=>
string(43) "<redacted>|<redacted>"
}
graph.facebook.com/<page_id>/posts?access_token=<redacted>|<redacted>"
string(183) "{"error":{"message":"Unsupported get request. Please read the Graph API documentation at https:\/\/developers.facebook.com\/docs\/graph-api","type":"GraphMethodException","code":100}}"
Can anyone verify a correct way to query a Facebook page programmatically, perhaps there's a setting in the page I'm querying that I need to set (although I can't find anything)?
If page restrictions apply, the page's feed can only be retrieved with an user access token as far as I know (because FB needs to evaluate the visibility criteria, and setting your app to the same restrictions doesn't help here):
See
https://developers.facebook.com/docs/graph-api/reference/v2.4/page/feed#readperms
It looks like everything you have done is correct. The response you got can be (i am not sure) because you got your clients pageid wrong.

After AccountManager..getAuthToken, how to send that token to its provider to authenticate something?

We're writing an app with an Android view and a website. Our app needs to associate some data with Facebook, Google, or Twitter (call them 'FGT'), and then hit the associated service to return true if that data is authenticated. The control flow is...
Android generates some data
User selects an FG or T account
getAuthToken
upload the data+token, via HTTPS POST, to our website
Our website (in Django, not that it matters) sends the Auth Token to FGT
FGT returns true if it likes that token, and false if it doesn't
The goal is preventing an attacker from concocting data and throwing it at our site with curl. And we /don't/ need to upload the data all the way to F, G, or T. We don't need to go all the way to a Hybrid App, where our webservice authenticates itself to F, G, or T, and then uses F, G, or T's API to post, e-mail, or tweet in the user's name.
There's obviously a simple answer for this out there somewhere; hopefully just three URIs, one each for F, G, or T, into which I can insert the Auth Token. That's why I would prefer NOT to download and install the SDK for each of Facebook, Google, and Twitter, and then write tons of service-specific code for each case. That would clutter up the code, and leave me screwed when the client requests Tumblr or MSN.
(A related question: What's the second parameter of getAuthToken()? "ah"? "mail"?)
So, while I continue to read books, source code, and SO posts showing how to do hard things the hard way, can someone tip me off how to do an easy thing the easy way?
The thread "validating Android's authToken on third party server" answered the sub-question "what simple URI to hit to test a token?"
The magic uri, for Google, is: https://accounts.google.com/o/oauth2/tokeninfo?access_token=%token_here%
The next question is How to thump an Access Token out of getAuthToken. The scope there should be the minimum possible to show a user really lives here:
String SCOPE = "oauth2:https://www.googleapis.com/auth/userinfo.profile";
am.getAuthToken(a, SCOPE, false, this, null);
My this class implements AccountManagerCallback<Bundle> and provides the method run(AccountManagerFuture<Bundle> result). That, per documentation such as "Android AccountManagerFuture getResult gives IOEXcelption when trying to get authorization token", might call startActivity() to challenge the user to authorize this activity, or it might use a token that's already stored in the AccountManager. (And note that implementing a class just to call-back yourself is pernicious, especially if the target method's named merely run(), so do as I say not as I do, kids!)
The resulting token is 52 bytes long, beginning with 'ya29.', so it's _ probably _ an access_token, not 331 characters, which is probably an id_token.
The resulting token is not bound to any specific channel (where "channel" is one unique set of client, server, and scope). So, from a simple curl, I can hit that /tokeninfo URI with it, and get this (scrubbed) JSONic wisdom:
{
"issued_to" : "442575845966-mde4be7eingpb5pntfs839jipsetro6s.apps.googleusercontent.com",
"audience" : "424242424242-mde4ab7defghi5jklmn839opqrstuv6s.apps.googleusercontent.com",
"user_id" : "424242424242424242424",
"scope" : "https://www.googleapis.com/auth/userinfo.profile",
"expires_in" : 2272
}
And so this answer would have formed, for me, the missing link between all the other documentation I was trying to read. Aaand now I need to do it all again for Facebook & Twitter...
There is a simple URL.
Each authtoken is granted against a scope. Each scope allows the authtoken to do certain things. If you try to do something that the scopes permit, that thing will fail or succeed based on the validity of the authtoken.
The simplest scope to request is probably 'email'.
If you go to the Oauth2 Playground at https://developers.google.com/oauthplayground/ you can experiment with scopes and calls to get one that suits you. You'll be able to see the URLs that you then need to replicate in your app.

How to have users 'reconnect' with soundcloud on each page reload?

I'm using the Javascript SDK inside a node.js (Express) App.
Connecting Users works fine, but the connection does not persist between page reloads.
Is this the default behaviour, or is the User supposed to stay connected in new requests?
Do I have to use OAuth token authentication and if so, how can this be done with the JS-SDK?
Inside the "Permission"-Popup, Users are already logged in with soundlcoud, though.
(just have to click the "connect" button each time)
Figured I'd share my answer for those who are unsatisfied with the current answers for automated oauth:
Retrieving access_token:
I had to define get and set cookie functions and then I use the functions to set and retrieve a function holding the access token. I'm not going to give these functions for conciseness but you can easily find them with a google search. I then use this line of code to get the SC access token (once the user has authenticated for the first time)
SC.accessToken()
Setting token:
So this is kind of just an elephant in the room in my opinion that for some reason no one has mentioned. How in the **** do you connect w/ SC using the access token? Do you set it as oauth param? On each call pass it? Well, after experimenting with putting the parameter in every single place I could think, I found out you have to do something like this:
SC.initialize({
client_id: '[removed for security reasons]',
client_secret: '[removed for security reasons]',
redirect_uri: '[removed for security reasons]',
access_token: getCookie("sc_lm2"),
scope: 'non-expiring'
});
//Where "sc_lm2" is the name of my cookie
Hope the helps! Took me a while to figure this out for such a simple thing
EDIT
Using PHP and Wordpress:
$json = wp_remote_get("http://api.soundcloud.com/users/[user_id]/tracks.json?client_id=[client_id]");
$soundcloudData = json_decode($json['body'],true);
(substitue cURL functionality if you're not using Wordpress). #krafty I assume you would just change the endpoint from "/tracks" to "/users" but I can't say I have ever really needed to grab anything but tracks using the Soundcloud API. Hope this helps, though I'm not sure I fully understand what it is that you are trying to accomplish (or rather, how exactly you're going about it) - are you trying to allow user logins? If you want to explain fully what you're trying to accomplish and the steps you're taking I'd be happy to take a crack at it.
Yep, this is the way to do it, officially. :)
For the Next SoundCloud site, we store the token in localStorage (until the user logs out, of course). In each AJAX request to the API from the front end, we put the oauth token in a request header:
jqXHR.setRequestHeader('Authorization', 'OAuth ' + the_oauth_token);

Trying to get OAuth dialog to work

I am at this step in getting my app started in the documentation:
https://developers.facebook.com/docs/appsonfacebook/tutorial/#auth
In there is a code block that (supposedly) forwards the user to a request dialog asking permission to access certain bit of information about them. I've placed this code block into the PHP script that my canvas URL points to, and changed the $app_id and $canvas_page to my application ID and canvas URL respectively. Instead of getting the expected dialog, I receive this following error from facebook:
"An error occurred. Please try again later."
No other details about the error are present. I've tried some variations of the script, and have even tried loading up this URL directly just to see if that would work. Note that I've replaced YOUR_APP_ID and YOUR_CANVAS_PAGE with the appropriate values and made sure that spelling and/or punctuation are correct:
https://www.facebook.com/dialog/oauth?client_id=YOUR_APP_ID&redirect_uri=YOUR_CANVAS_PAGE&scope=email,read_stream
For the redirect URL, I've tried prepending it with http://, https://, and no prefix at all. All with the same result.
My question: is the example in the documentation broken, or is the oauth link provided in the documentation currently down? The vague nature of the error is somewhat frustrating since I can't tell if it's something I'm doing wrong or if it's facebook's oauth function that's at fault.
So, the problem was that instead of using the numeric application ID that facebook assigned for me when I originally created the app as the YOUR_APP_ID parameter in the OAuth URL, I was using the application namespace string. Facebook didn't understand this sort of request, and returned the generic error message.
Once I used the numeric app ID, the OAuth dialog popped up to ask permission to access my account, as expected.

How can I retrieve Facebook User Info without Access Token

I found a good tutorial for building Facebook membership Authentication website which demo file is here > http://niftyandcrackerjack.com/sites/default/files/Test.zip
I wonder this example does not use access token to retrieve Facebook User Info. It use classes inherits from the masterpage. As I am new to ASP.NET, I don't know how to retrieve Facebook user info. Can someone give me and suggestion or explain...... Thanks,
My finding so far indicate that basic information cannot be accessed unless one has either 'userid' or 'username' as in this post.
If one has to try and fetch basic information using following url, then access_token is needed
http://graph.facebook.com/me
Perform an HTTP GET to https://graph.facebook.com/{userid} or HTTP GET to https://graph.facebook.com/{username}
Examples: Click the link below to see the JSON response.
https://graph.facebook.com/4
https://graph.facebook.com/zuck
Pretty cool, eh? And no token needed to get at this public info.
You can get more info on this here: https://developers.facebook.com/docs/reference/api