Different Facebook access token JavaScript SDK - facebook

I'm quite confused with the access token from facebook..here is how I obtain the user's access token and use it to get data from graph API
window.fbAsyncInit = function() {
FB.init({
appId : 'app ID',
status : true,
cookie : true,
xfbml : true,
oauth : true,
});
FB.getLoginStatus(getStatus);
FB.Event.subscribe('auth.authResponseChange', getStatus);
function getStatus(response) {
if ( response.status === 'connected' ) {
var accessToken = response.authResponse.accessToken;
console.log("accessToken = " + accessToken);
$.ajax({
dataType : "jsonp",
type : "GET",
url : "https://graph.facebook.com/me/albums?access_token=" + accessToken,
success : function(data) {
$.each(data, function(index, value) {
console.log(index + ": " + value);
})
}
});
}
}
};
However, I always get an empty data. After I visit the graph API documentation here: https://developers.facebook.com/docs/reference/api/ and click on one of the graph links, I notice that the access token generated there is always different from what I retrieve from my code. For example, the current access token in the graph api documentation is
"AAAAAAITEghMBAMwuyHZCO3VOAvCm9hHpaZC9PGV9238ixsZB7zSfuplZBTZCLRj6cEViZADJlVcjOfInwvcbhqu3XBF1w4ZAxvPbexcGQZAYzb4bHAKsMbLF"
and the one in console log is
"AAAG0ZCFantJ8BAAFcMdDOyDyT4OBtjrvULEaS2o94gZAU7U1xITaogFXCZBghQP8G9bjEh3XSCATQOZCUSZCuNWFvEfypIAmcz9bkbk5qRBlHUZAOE4guW"
I think that I may have done this the wrong way. Can anyone help explain to me how to retrieve data from graph API in a correct way?
Any kinds of help will be appreciated. Thanks in advance :)

Run this URL with your authToken first:
https://graph.facebook.com/me/permissions?access_token=USER_ACCESS_TOKEN
You'll almost certainly only see basic permissions in the response, which is why you aren't getting the data from your call to the user's album.
You'll then want to run your user through the Authentication Process, making sure you request the permissions you need (probably 'user_photos' in your case).
More info is available in those two links. Good luck!

access token will never be the same. So that behaviour is correct.
Back to your problem , I think its mostly scope related issue.

I had developed a application using facebook c# sdk, In that application i did it like this:
when a post is to be submitted , redirect the user to facebook (with some parameters like appid, app-secret, auth-token and
redirect-url);
Facebook will ask the user to login with his credentials.
When the user is logged in, facebook will redirect back to the redirect-url. (with the authtoken and a new auth-code).
Then we should use this auth-code, app-id and app-secret and obtain the user-access-token. (This is done by doing a rest api call to the
url
https://graph.facebook.com/oauth/access_token?client_id=client_id&redirect_uri=redirect_uri&client_secret=client_secret&code=auth-code
This will return the user-token and expiry time for the token
And then we can post using this user-access-token to the fb.
Initially i had misunderstood the auth-code and used it as the user-access-token, and i always got the result as unauthorised token .
Please check whether this will help you or not.

Related

Facebook api - invalid token

tried to send post to facebook api to scrape my page at load.
http://i.stack.imgur.com/3Jd0y.png
what is wrong with my code?
This is how you use FB.api:
FB.api('/', 'post', {
id: 'url-to-scrape',
scrape: true
}, function (response) {
console.log(response);
});
Not sure where you got that code example from, but you should always take a look at the Facebook docs.
I you are getting invalid token means your token is not correct let me tell you how to generate token it is simply by combining your app id and app secret gotten on Facebook developers app dashboard after you have signed up check here and read url and to check errors faster on your code api, download post man here www.getpostman.com, put in your api call code in the url bar and hit send it will tell you your error. Then to get token for facebook fancount,pageid,likescount, you can do a search for more info on graph.facebook.com on google. contact me if there is problem.
$appid = "xxxxxxxxxxxxxxx";
$appsecret = "yyyyyyyyyyyyyyyyyyyyyyyyy";
//get it from your dashboard
$token = $appid .|. $appsecret key

Doubts about Security in Login for Web with Facebook Oauth JavaScript SDK that send ACCESS TOKEN to server

I have doubts about security of my process of authentication oauth with facebook..
I use login for web with javascript sdk with fb button:
I get an Access Token successfully and pass it to server(calling check_facebook_session.php) to make API call to Facebook Provider..
In the following code there is also the log in console of access token.
Everything works!!! on the server I use the php sdk to call the API REST with APPID, APPSECRET and ACCESS_TOKEN:
**
Now my question, have I a security problem?
Is a bad idea to pass the token to the server?
The token that is visible on the client can be used WITHOUT APP SECRET to get information about the user logged?
**
Note: Google+ Sign-In for server-side apps Implementing the one-time-code flow with step:
- Include the Google+ script on your page.
- Add the sign-in button to your page.
- Sign in the user.
- Send the authorization code to the server.
as explained in: https://developers.google.com/+/web/signin/server-side-flow
Unlike facebook google in the js client return a CODE, not an ACCES TOKEN and the server receive and use it to request ACCESS TOKEN.
Thanks..
Following is the javascript code for facebook:
window.fbAsyncInit = function() {
FB.init({
appId : FACEBOOK_APP_ID, // App ID
status : true, // check login status
cookie : false, // enable/disable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.Event.subscribe('auth.authResponseChange', function(response)
{
if (response.status === 'connected')
{
var accessToken = FB.getAuthResponse()['accessToken'];
console.log(accessToken);
$.ajax({
type: 'POST',
url: check_facebook_session.php,
contentType: 'application/x-www-form-urlencoded; charset=utf-8',
processData: false,
data: 'token=' + accessToken,
success: function(result)
{
if(result == 'SUCCESS'){window.location.href = fb_callback_url}
},
error: function(xhr)
{
alert('Request Status: ' + xhr.status + ' Status Text: ' + xhr.statusText + ' ' + xhr.responseText);
}
});
}
else if (response.status === 'not_authorized')
{
FB.login();
}
else
{
FB.login();
}
});
};
// Load the SDK asynchronously
.......
}(document));
I did some testing and came to the conclusions that I hope can be useful.
In Facebook SDK for JavaScript it automatically handles access token storage and tracking of login status, so apps using it do not need to create their own mechanisms for doing so, and can proceed to making API calls.
The system seems safe because I believe that the callback url of the call is the site that host the page and configured between those of the facebook application, so I can change the application id in the javascript code but the sdk response with error message and get the user's token pretending to be another application. This was already obvious to those who know the flow :-)
Passes the token to the server is definitely a bad idea because it can be snorted and used by simply calling https://graph.facebook.com/me?access_token=... to get user information, In the different flow of google the token is not passed but is passed the code necessary to obtain it.
The best solution to use advantage of client and server is it:
Used in conjunction with the Facebook SDK for JavaScript,
the PHP SDK can share user sessions seamlessly across the client and server.
If people are logged in with Facebook and have authorized your app,
the JavaScript SDK can pick up the user session and persist this in a cookie,
which the PHP SDK reads without any intervention on the developer's part.
To enable this functionality, ensure that when you embed and initialize the JS SDK,
you set both the status and the cookie parameters of the object passed to FB.init() to true.
Regards..
i think it is secure because the user's data is only returned with connected status after user authentication with facebook.
https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/
I have followed Facebook example on getting access token by using $fb->getJavaScriptHelper();
https://developers.facebook.com/docs/php/howto/example_access_token_from_javascript
$helper = $fb->getJavaScriptHelper();
$accessToken = $helper->getAccessToken();
echo $accessToken->getValue();
P.S. Add try{} catch() {} blocks, as in Facebook example for error handling.

Should I pass access token when using FB.api()?

I'm just a little confused as to how to pass my access token into FB.api() when making requests for protected things.
I'm getting my app to login and authenticate fine, but how do I use FB.api() with the access token I have?
app.accessToken = response.authResponse.accessToken; // This is a valid access token.
FB.api('/me/friends?access_token='+app.accessToken, {fields: 'name,id,location,picture,installed'}, function(response) {
console.log(response);
});
Is that the correct way to pass in the access token to FB.api()?
In this case, my response comes back with the friends name,id,location,picture but it doesn't seem to have the 'installed' data as that is protected.
Am I doing this right?
Although I see why some users are saying you may not need to pass access token due to your specific use.
Generally, there are cases where you do need to pass an access token through FB.api()
The way this is done is by passing it in the parameter object, as such:
FB.api('/{fb-graph-node-goes-here}/, {
access_token: "TOKEN GOES HERE"
//other parameters can go here aswell
}, function(response) {
console.log(response);
});
You do not need to pass the token, if the user logged in (with FB.login, for example). In fact, by using the JavaScript SDK (or PHP SDK), you almost never need to deal with the (user) access tokens.
So, your call would just be like this:
FB.api('/me/friends', function(response) {
console.log(response);
});
Getting the info if the user installed the app:
Test if user has application installed with Graph API
How to fetch a list of the current users' friends who also use my app?
That is how I did it:
Pass access_token as a parameter.
FB.api("/me", { access_token : response.authResponse.accessToken }, {fields: ['last_name', 'first_name', 'name']},
function (response) {
console.log(response);
console.log('Name: ' + response.name);
}
);
You would need to pass access token if requesting for extending fields. Please refer to
https://developers.facebook.com/docs/facebook-login/permissions/v2.0#reference-extended-profile

log on to facebook through extension

I've already registered my app on Facebook developer and got an ID, but had hard time to characterize the my app(chrome extension), it's website app, mobile app, facebook app? What I wanna do is a simple extension that allows users simply to click on it, and the background JavaScript calls the Facebook API to ask the users to log in like this.
window.fbAsyncInit = function() {
FB.init({
appId : '123456789',
status : true,
cookie : true,
xfbml : true,
oauth : true,
});
};
chrome.browserAction.onClicked.addListener(function(tab) {
FB.login(function(response) {
if(response.authResponse) {
alert('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
});
} else {
alert('User cancelled login or did not fully authorize.');
}
});
});
However, it pops up a window that says an error occurred, it is another way of saying "I am not authorized", how do I specify my app's URL on the Facebook developer page, because the extension's URL is a garbage like this chrome extension://asdjlajsldj/ or anyone knows any workaround? Thank you
I would assume that Facebook's API uses OAuth 2 to let applications access users data. Google provides a way of doing this with an example in their API section. I have also have posted an alternative method on GitHub. Note that my method will require some alternations to fit Facebook's interface but the idea is the same (I have a GitHub branch to do this with GitHub).
Essentially your extension must get an access token for the user from Facebook, then using this token as a parameter you can query private data from the API. What makes it seem difficult is the fact the the chrome extensions are sandboxed and have no return URL, but using one of the two methods above should do you just fine.
Good Luck!

How to retrieve the facebook oauth 2.0 access_token

I am trying to get the access_token of the logged in facebook user.
I get something like this.. url followed by the code i am retrieve the code..
it says in the guide to exchange it for access_token...
https://graph.facebook.com/oauth/access_token?
client_id=XXXXXXXXXXXXXX&
redirect_uri=http://www.my-site.com/&
client_secret=XXXXXXXXXXXXXXXXXXXXX&
code=2.hJFWoMlLf3tLOSos_qNCBg__.3600.1279836000-10000100XXXXXXX|kGwPB4y5K_-ijD9_1CfjSpT-oaY..
How i can exchange it for a access_token using what FB.api or jquery or javascript..
When i plug this url in the address bar.. i am able to see access_token..
I appreciate if somebody can tell me how to retrieve the access_token using javascript or jquery.
Thanks.
According to Facebook, and my personal experiences with the api, the FB.getSession() function is deprecated and should throw an exception if called.
From facebook:
The FB.getAuthResponse method is a replacement for the FB.getSession method which was deprecated after the migration to OAuth 2.0.
Instead you should use the getLoginStatus callback -
FB.getLoginStatus(function(response) {
var token = response.authResponse.accessToken;
});
//Example structure of response object
var eg =
{
status: 'connected',
authResponse: {
accessToken: '...',
expiresIn:'...',
signedRequest:'...',
userID:'...'
}
};
source: http://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/
If you are using the JavaScript SDK, then after logging in the user, getting the access token in your JavaScript code is as simple as:
FB.getSession().access_token
However, getSession may return null if a user is logged out, so the proper way is to first check for null before accessing the token.
var session = FB.getSession();
if(session != null) { // user is still logged in
console.log(session.access_token);
}