Facebook javascript + php, How to ensure the validity of the data? - php

Im using the javascript SDK of facebook in the frontend:
jQuery("#pct_fbbutton").live("click",function(){
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
console.log('Conected');
FB.api('/me/likes', function(response) { user_likes = response;
FB.api('/me', function(response) { user = response;
send_server(user, user_likes);
});
});
} else if (response.status === 'not_authorized') {
console.log('not_authorized');
login();
} else {
console.log('not_logged_in');
login();
}
});
});
As you can see, after the user is login with facebook ill send two objects via AJAX to a php script (using the function send_server).
I can access in the backend the currently generated token with $facebook->getAccessToken(), but as I know this is retrived from a cookie made by the javasript sdk, considering that all frontend data can be hacked, using the token how can ensure that the user data is valid on php?

The answer is to perform the graph calls with PHP instead of JavaScript, especially if the only purpose of your client-side script is to send it to the server;
Doing the data gathering on the server is the only practical way you can be sure that the data has not been tampered with, assuming you do proper https certificate checking.
The validity of the access token is also easy, because Facebook will return an error if the provided access_token value is invalid.

Once you retrieve the access_token in the back end, try to fetch the user's profile. If the fetch was successful, then the client provided you with the correct access_token and you should save it. Something like the below example should work, but you can find many more examples:
<?php
$facebook = new Facebook(array(
'appId' => $initMe["appId"],
'secret' => $initMe["appSecret"],
));
$facebook->setAccessToken($initMe["accessToken"]);
$user = $facebook->getUser();
if ($user) {
$user_profile = $facebook->api('/me');
print_r($user_profile);
}
?>

Related

How can facebook php sdk get the access token from javascript sdk?

FacebookI am using facebook javascript sdk to loigin a user, and then I wish to get some of his info via the php sdk, but I keep getting "An active access token must be used to query information about the current user."
this is the relevant html/js code:
<script>
window.fbAsyncInit = function() {
// init the FB JS SDK
FB.init({
appId : '8', // App ID from the app dashboard
channelUrl : '//url/frontend/channel.php', // Channel file for x-domain comms
status : true, // Check Facebook Login status
cookie : true,
oauth:true,
xfbml : true // Look for social plugins on the page
});
FB.Event.subscribe('auth.authResponseChange', function(response) {
if (response.status === 'connected') {
submitform();
} });
};
function submitform() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me?fields=email,name', function(response) {
//submits a form from this page...
});
}
</script>
Facebook
and the php that fails is :
$facebook = new Facebook(array(
'appId' => Configuration::$facebook_app_id,
'secret' => Configuration::$facebook_app_secret));
// Get User ID
$user_profile = $facebook->api('/me?fields=name,id','GET');
It seemed to work for a while, and then it breaks with
" [message] => An active access token must be used to query information about the current user.
[type] => OAuthException
[code] => 2500",
Anyone has an idea how to stabilize this?
Thanks
Maybe that happens because your acces token was expired?
There are several access token types. And if your access token is a "short-term token" - you must refresh it.
you can read abot acces tokens here https://developers.facebook.com/docs/facebook-login/access-tokens/
In python server lib for facebook i used method fetchToken(appId, secret) to refresh my expired token.

Is the FB PHP SDK's getAccessToken() a reliable way to retrieve a user's auth token?

So I have a FB app and in some situations I need my Javascript to load content into a div using a php file that lives in the same domain as index.php. For some of these I like to make sure that the user is still valid and/or have need of an auth token and FB user id. I achieved this by making creating an instance of the FB PHP SDK in the php file being ajax injected by the javascript and using getUser() and getAccessToken(). I have noticed, however, that sometimes inexplicably the getAccessToken() call will fail and report that it needs a valid access token to perform the action.
Is getAccessToken() a reliable (or even ideal) way to ensure a user is logged into FB or should I be doing something else (e.g. storing the access token I parse from the signed request in Javscript and passing it as a variable to the php files I am injecting)? Thanks.
Most reliable would probably be to get their details. I have, in hte past, had an instance of "getUser" return true, but the user has not actually logged on. So now I also get all their details and this works more reliably:
$facebook = new Facebook(array(
'appId' => FB_APP_ID,
'secret' => FB_APP_SECRET,
'cookie' => true
));
$FB_UID=false;
try {
$FB_UID = $facebook->getUser();
// This verifies the user is actually logged in. teh above can return "true" but the following will crap out and throw exception
$FB_me = $facebook->api('/me'); // 'birthday'
// Not needed:
// $FB_token = $facebook->getAccessToken();
} catch (FacebookApiException $e) {
$FB_UID = false;
$FB_me = false;
// $FB_token = false;
}

Re-Authenitcating a facebook user once logged in

Given that a Facebook user has logged in at some point in your Facebookapp (using fb.login) and that user has been saved in the database. How can you let the user re-authenticate with you app again after the accesstoken has expired (fb.api('/me') fails).
The signed request holds the user id, but how do you log in the user from there?
I'm using the PHP sdk and I basicly check with FB.api('/me') right in the beginning to either direct to a welcome page or the users page. But FB return false in some cases, usually after a day or 2. So I started to think it was because of the Accesstoken has expired. I have no clue how to re-authenticate, I only have knowledge that the user id still resides in the signed request.
Put following code in your javascript...it will open login popup if user is not logged in
FB.getLoginStatus(function(response) {
if (response.authResponse) {
fbUserId = response.authResponse.userID;
token = response.authResponse.accessToken;
} else {
FB.login(function(response) {
if (response.authResponse) {
fbUserId = response.authResponse.userID;
token = response.authResponse.accessToken;
}
else {
console.log('User cancelled login or did not fully authorize.');
}
});
}
},true);
Use the Javascript SDK to prompt the user to login via Facebook:
https://developers.facebook.com/docs/reference/javascript/FB.login/
Alternatively, you could try storing the code returned by Facebook during server-side auth and use it to request a new token when the user returns.

Facebook JS SDK & PHP SDK without refreshing?

I currently have the facebook js sdk to login to the site and then I want to use the PHP sdk for everything else. How can I pass the accessToken to the PHP SDK to allow me to do this? I want to pass it to a PHP script at a different url, so for example I login at /login/ and then open up a modal box to /facebook/?accessToken=gfdhjsfghjkfgdh or what ever.
http://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/
Please check this link.
A sample code may look like this,
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
//got the token
var accessToken = response.authResponse.accessToken;
//send it to php via _GET
window.location = "/facebook/?accessToken=" + accessToken;
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
//but not connected to the app
} else {
// the user isn't even logged in to Facebook.
}
});
You can get the accesstoken then send it to php.

one time authentication for weblink with facebook app

i want to authenticate my facebook profile with my website so i can pull infor from the page.
i was suggested to one time authenticate with the facebook api through a temp page. somewhat like:
<fb:login-button params="some permission" />
i am new to coding facebook apps. but this seems like fbml. how can i use it to authenticate my website with my own profile. i dont need users to log into my website. i just need to pull info from my page.
the facebook documentation is sparse and fragmented. all i got for the Login was this code fragment. I dont understand how i can authenticate a weblink through this method.
FB.login(function(response) {
if (response.session) {
// user successfully logged in
} else {
// user cancelled login
}
});
can anyone throw some light??
Let's start from the beggining:
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml" xml:lang="en" lang="en">
It's required for fbml to work. Next:
<fb:login-button autologoutlink="true"></fb:login-button>
<div id="fb-root"></div>
These two lines create the "facebook login button", you should place them in your html where you want the button to appear.
Right before your closing body tag add:
<script type="text/javascript" src="https://connect.facebook.net/en_US/all.js"></script>
<script>
window.fbAsyncInit = function() {
FB.init({appId: 'YOUR APP ID HERE', status: true, cookie: true, xfbml: true});
FB.Event.subscribe("auth.login", function(response) {
if(response.session) {
// this is where you handle facebook's response
}
});
};
</script>
What you are doing here is first initializing the connection to facebook, with your app id (you need to create an application), and register an "auth.login" event. The auth.login event is triggered every time you click the facebook login button and successfully login to facebook, or facebook auto logins you based on their cookie.
You can find an explanation of the auth.login and other events here, look at the sidebar at the left, all events are listed.
The response is JSON formatted and it contains your basic session information:
{
status: 'connected',
session: {
access_token: '...',
expires:'...',
secret:'...',
session_key:'...',
sig:'...',
uid:'...'
}
}
You can read more about it here. If your status is indeed "connected" the next most important bit of information is the uid, this is your unique facebook identifier, a public id with which you can send further requests to facebook. What you do with the response is up to you. An obvious choice would be to send it via ajax to a script that logs you in your application.
To get more info from facebook you need to download the php sdk. To use the sdk:
<?php
include_once "facebook-sdk-3.0.0/src/facebook.php";
$appID = "YOUR APP ID";
$appSecret = "YOUR APP SECRET";
$cookie = "fbs_{$appID}";
$cookie = isset($_COOKIE[$cookie]) ? trim($_COOKIE[$cookie], '"') : "";
if(empty($cookie)) {
echo "no facebook cookie";
die();
}
parse_str($cookie, $data);
$facebook = new Facebook(array(
"appId" => $appID,
"secret" => $appSecret,
"cookie" => true
));
$facebook->setAccessToken($data["access_token"]);
$user = $facebook->getUser();
$profile = $facebook->api("/me");
?>
So at first you parse facebook's cookie which is named "fbs_YOUR_APP_ID" and contains your session information (url encoded). What you actually need is the access_token (a unique identifier of the authenticated session), which was also returned to you in the JSON response object before. Then via the Facebook object you can do and api requests you want.
Now to have a full authentication mechanism you should create a similar connect script that instead of getting the session information from the cookie it should take them from the response object that is returned when auth.login occurs (possibly via ajax).
You should read the Authentication workflow document to better understand how facebook connect works.
A good and easy way to deal with Facebook authentication is to implement the server side flow with the Facebook PHP SDK (see on github). So you will have something like :
require "facebook.php";
$facebook = new Facebook(array(
'appId' => YOUR_APP_ID,
'secret' => YOUR_APP_SECRET,
));
$user = $facebook->getUser();
If the user is logged in, then $user is his Facebook ID. You then have to check if you have a valid access token by making an API call :
If it does not raise any exception, then you have a valid access token
If it does, then you have to re-authenticate the user.
Here :
if ($user) {
try {
$facebook->api('/me');
} catch (FacebookApiException $e) {
$user = null;
}
}
You need then to display the login or logout link :
<?php if ($user): ?>
Logout of Facebook
<?php else: ?>
Login with Facebook
<?php endif ?>
When the user is logged in and you have a valid access token, you can make API calls to get data from Facebook :
$user_profile = $facebook->api('/me');
You may want to check the example page of the Facebook PHP SDK which is well documented.
Hope that helps.

Categories