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

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.

Related

Facebook pixel events call from server

I have absolutelly the same question as dan here - Facebook conversion pixel with "server to server" option . There was written, that there was no way, but it was 2013, so I hope something changed.
So, is there any way to call facebook pixel events (e.g. CompleteRegistration) from server side now?
I can describe situation in more details. Imagine, that user visits our site, where fb pixel tracks 'PageView' of course. When user passes form and sends his phone number, we call 'Lead' event. But then we need to track one more event, when our manager successfully confirmes this user! Of course, it happens on other computer and so on, so there is no idea, how to "connect" to base user.
I've seen a lot of documentation departments like this, but I can't fully understand even if it's possible or not.
Logically, we need to generate specific id for user (or it can be phone number really), when 'Lead' event is called. Then, we should use this id to 'CompleteRegistration' for that user. But I can't understand, how to do it technically.
It would be gratefull, if somebody could explain it.
P.S. As I understand, it is fully available in API for mobile apps. Is it ok idea to use it for our situation, if there is no other solution?
Use Offline Conversions to record events that happen after a user has left your website. Logging these conversions, technically, is very easy. Setting everything up takes a little effort
tldr; check the code below
Follow setup steps in the FB docs (Setup steps 1-5) which are:
Setup facebook Business Manager account
Add a new app to Business Manager account
Create an Ad account, if you don't already have one
Create a System User for the ad account
After the setup, follow Upload Event Data steps on the same page, steps 1-3 to create an offline event set and associate it with your ad. These can be carried out in the Graph API Explorer by following the links in the examples. These can be done programmatically, but is out of the scope of making the event calls from the server for one campaign.
Once you have created the event set, then you can upload your CompleteRegistration events!
You will need to make a multipart form data request to FB, the data key will be an array of your conversion events. As #Cbroe mentioned, you must hash your match keys (the data you have available about your user to match them with a FB user) before sending to FB. The more match keys you are able to provide, the better chance at matching your user. So if you can get their email and phone at the same time, you're much more likely to match your user.
Here's an example of the call to FB using node.js:
var request = require('request')
// The access token you generated for your system user
var access_token = 'your_access_token'
// The ID of the conversion set you created
var conversionId = 'your_conversion_set_id'
var options = {
url: 'https://graph.facebook.com/v2.12/' + conversionId + '/events',
formData: {
access_token: access_token,
upload_tag: 'registrations', //optional
data: [{
match_keys: {
"phone": ["<HASH>", "<HASH>"]
},
currency: "USD",
event_name: "CompleteRegistration",
event_time: 1456870902,
custom_data: { // optional
event_source: "manager approved"
},
}]
}
}
request(options, function(err, result) {
// error handle and check for success
})
Offline Conversion Docs
Facebook has now a Server-Side API: https://developers.facebook.com/docs/marketing-api/server-side-api/get-started
Implementing this is similar to implementing the offline events outlined in the accepted answer.
Keep in mind that it will always be cumbersome to track and connect events from the browser and from your server. You need to share a unique user id between the browser and server, so that Facebook (or any other analytics provider) will know that the event belongs to the same user.
Tools like mixpanel.com and amplitude.com may be more tailored to your needs, but will get very expensive once you move out of the free tier (100+ EUR at mixpanel, 1000+ EUR at Amplitude, monthly). Those tools are tailored towards company success, whereas Facebook is tailored towards selling and measuring Facebook ads.

Getting a user access token in facebook using Koala

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.

GitHub OAuth in lua

I am working on a library in LUA for an ipad app called Codea. I'm trying to figure out to use OAuth for GitHub Gists. Only part that i can not figure out is how to get an Auth token via code. I used curl in terminal to get myself a token but this seems to be to much work for other users.
I've read through the github api docs multiple times but I cant figure out how to get a Token programmatically. I've tried to duplicate the method I've used to GET and POST gists but it does not seem to work. I'm not sure how to pass the username and password.
I'm creating a table with the needed params then encoding it in json. Everything I try gets a 404 error or 500 error. Thank you all in advance.
local url = "https://api.github.com/authorizations"
local d = {}
d.scopes = {"gist"}
d.note = "AutoGist Codea"
projectAuth = json.encode(d)
opts = { data = projectAuth }
opts.method = "POST"
opts.headers = {Authorization = "basic " .."username:password"}
http.request(url,successCallback,failedCallback,opts)
Scopes are coming, but only in Q4 2013.
See "OAuth changes coming" (October 2013, by Tim Cleam - tclem):
Starting today, we are returning granted scopes as part of the access_token response.
For example, if you are making a POST with the application/json mime-type you’ll see an additional field for the granted scopes.
{
"access_token":"e72e16c7e42f292c6912e7710c838347ae178b4a",
"scope":"repo,gist",
"token_type":"bearer"
}
Right now, these scopes will be identical to what you requested, but we are moving towards a feature set that will allow GitHub users to edit their scopes, effectively granting your application less access than you originally requested.
You should be aware of this possibility and adjust your application behavior accordingly.
Some things to watch out for and keep in mind:
Most third party applications using GitHub OAuth to identify users have the best success in adoption by starting out with a request for the minimum access that the application can possibly get away with.
Something like no scopes or just user:email is very sane.
It is important to handle the error cases where a users chooses to grant you less access than you originally requested.
Now that we are surfacing the granted scopes on the access_token response, applications can warn or otherwise communicate with their users that they will see reduced functionality or be unable to perform some actions.
Applications can always send users back through the flow again to get additional permission, but don’t forget that users can always say no.

Always get "Error validating verification code." when requesting access_token

Well, I have done all my best to try to solve this problem, but, still, it's too annoying.
I decided to use OAuth with server-side authentication. So, I have followed Facebook documentation, and I have done the following step.
Create a link which redirect people to log in Facebook by https://www.facebook.com/dialog/oauth?client_id={APP_ID}&redirect_uri=http://abc.com/nextStep.php
In nextStep.php, redirect people to https://graph.facebook.com/oauth/access_token?code={CODE GENERATED BY FACEBOOK}&client_id={APP_ID}&redirect_uri=http://abc.com/thirdStep.php&client_secret={APP_SECRET}
The problem exists when proceeding to step 2. The page shows that:
{
"error": {
"message": "Error validating verification code.",
"type": "OAuthException",
"code": 100
}
}
I have googled for lots of time. Some people suggests to add a trailing slash in the redirect_uri, but it doesn't work. What should I do? And how can I get the user information after getting the access_token? Thanks for your help.
Two things:
First, I’d say you’re missing the state parameter in your first URL … you have to make up a value that the docs describe as SOME_ARBITRARY_BUT_UNIQUE_STRING – some unique id/hash/whatever, that no one from the outside would be able to guess. (Yes, that parameter is optional – but you should use it anyway, because as the docs say it helps prevent CSRF and is therefore an important security measure. If you don’t know what CSRF means, please look it up.)
And second, in your step two, you should not redirect the user’s client to that address, but make a server side call to that endpoint instead. You are putting your app secret into this URL (that’s not the mistake, you have to) – so it would be easy for the user to get it if you called that URL in his browser …!
I’d suggest you start with https://developers.facebook.com/docs/authentication/server-side/ again, reading it carefully from the top – you can hardly go wrong if you really follow the instructions given there one-by-one …

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);