I am successfully using the Facebook SDK (PHP) to connect users to my site, but I'm having issues when they authenticate their account. Their account is successfully authenticated, but for some reason my site's sessions are cleared.
Flow:
User logs into my site (local username and password)
User connects to Facebook in a popup
Facebook authenticates user and returns back to my site
My sites session is now invalid (both in the popup and main window) causing the user to be logged out
I am using the Facebook SDK (PHP) and my site uses the CakePHP framework
Any help will be greatly appreciated.
I can't tell you what is deleting your session, but you might want to try this (works for me)
use the Javascript SDK to display the login buttons that will open the popup to connect to FB
add the js SDK to your page like this:
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({appId: '<?php echo FB_API_ID; ?>', status: true, cookie: true, xfbml: true});
FB.Event.subscribe('auth.login', function() {
new Request({
'method': 'get',
'url': '<?php echo $this->Html->url(array('controller'=>'users','action'=>'login_fb'));?>',
'onSuccess': function(result){
window.location.reload();
}
}).send();
});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
On the auth.login event i'm using an ajax call to /users/login_fb that will use the Facebook SDK to check the facebook session:
App::import('Lib', 'facebook_sdk/facebook');
// "MyAuth" is a custom Auth Component that extends the normal Auth component
$this->MyAuth->facebook = new Facebook(array(
'appId' => FB_API_ID,
'secret' => FB_SECRET,
'cookie' => true,
));
$me = null;
$session = $this->MyAuth->facebook->getSession();
if ($session) {
try {
$uid = $this->MyAuth->facebook->getUser();
$me = $this->MyAuth->facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
}
}
if ($me) {
$this->Session->write('FbLogin.session',$session);
$this->Session->write('FbLogin.user',$me);
$UserModel = ClassRegistry::init('User');
$user = $UserModel->findByUid($me['id']);
if(!$user){
$UserModel->create();
$user_data = array( 'username'=>$me['username'],
'name'=>$me['first_name'],
'lastname'=>$me['last_name'],
'email'=>$me['email'],
'group_id'=>GROUP_VISITOR,
'uid'=>$me['id']
);
$UserModel->save($user_data);
$user['User']['id'] = $UserModel->id;
}
$this->Session->write($this->MyAuth->sessionKey, $user['User']);
$this->MyAuth->_loggedIn = true;
}
}
the main idea is that.. in js i call an ajax to check the fb session and then save it in the cake session , and the js will refresh the page
Could be worth checking the Cake security level, it might be doing referrer checks (I think it does this in the "high" setting, maybe the "medium" as well), which would be invalidating the session.
I couldn't find out why the session was being reset so decided not to use the SDK for the authentication. This is what I used instead.
$code = (isset ($_REQUEST['code']) ? $_REQUEST['code'] : null);
if (empty ($code)) {
$dialogUrl = 'http://www.facebook.com/dialog/oauth?client_id=' . $this->appId . '&redirect_uri=' . urlencode($this->url) . '&scope=' . implode(',', $this->scope);
header('Location: ' . $dialogUrl);
die;
}
else {
$tokenUrl = 'https://graph.facebook.com/oauth/access_token?client_id=' . $this->appId . '&redirect_uri=' . urlencode($this->url) . '&client_secret=' . $this->secret . '&code=' . $code;
$accessToken = file_get_contents($tokenUrl);
$this->Session->write('facebookAccessToken', $accessToken);
$graphUrl = 'https://graph.facebook.com/me?' . $accessToken;
$fbUser = json_decode(file_get_contents($graphUrl));
if ($fbUser) {
...
}
}
Related
I am trying to login a website by using facebook. For that I have taken the help of Facebook php SDK. For now my code looks like this
<div id="fb-root"></div>
<script type="text/javascript">
//<![CDATA[
window.fbAsyncInit = function() {
FB.init({
appId : 'xxxxxxxxxxxxxx', // App ID
channelURL : '', // Channel File, not required so leave empty
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
oauth : true, // enable OAuth 2.0
xfbml : false // parse XFBML
});
};
// logs the user in the application and facebook
function login(){
FB.getLoginStatus(function(r){
if(r.status === 'connected'){
window.location.href = 'fbconnect.php';
}else{
FB.login(function(response) {
if(response.authResponse) {
//if (response.perms)
window.location.href = 'fbconnect.php';
} else {
// user is not logged in
}
},{scope:'email'}); // which data to access from user profile
}
});
}
// Load the SDK Asynchronously
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
//]]>
</script>
<?php
require_once 'src/facebook.php'; //include the facebook php sdk
$facebook = new Facebook(array(
'appId' => 'xxxxxxxxxxxxxx', //app id
'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', // app secret
));
$user = $facebook->getUser();
if ($user) { // check if current user is authenticated
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me'); //get current user's profile information using open graph
}
catch(Exception $e){}
}
?>
<a href='#' onclick='login();'>Facebook Login</a>
Now with this code I can do login easily. But after this I need two more things.
Make a logout after login. So how can I make a logout function here
so that when a user will click on logout he will be logout from both
facebook and the site at a time.
How to get user info after login like his name, email id etc.
So can someone kindly tell me how to do this? I am just a newbie in facebook app. So any help and suggestions will be raelly appreciable. Thanks
To get the Logout URL u can try this:
$fbUserId = $facebook->getUser();
if ($fbUserId) {
$host = $_SERVER['HTTP_HOST'];
$params = array('next' => "http://{$host}/project/page.php");
$logoutUrl = $facebook->getLogoutUrl($params);
}
For Getting the User Details you can try this
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
return false;
}
return $user_profile;
I am using facebook SDK to get facebook friends list. If I Invoke API with Javascript FB.init(); it works perfectly fine..
but if I use it directly like
facebook = new Facebook(array(
'appId' => $appid,
'secret' => $secret
));
$fbuser = $facebook->getUser();
try{
$user_profile = $facebook->api('/me');
print_r($user_profile);
} catch(Exception $e){
echo $e->getMessage();
}
(User is logged in with facebook in the same browser)
It always gives me an error : An active access token must be used to query information about the current user.
Please help me how to use it without FB.init() or redirect anywhere..
Use this
facebook = new Facebook(array(
'appId' => $appid,
'secret' => $secret,
'cookie' => true
));
$fbuser = $facebook->getUser();
if($fbuser){
$access_token = $facebook->getAccessToken();
$facebook->setAccessToken($access_token);
try{
$user_profile = $facebook->api('/me');
print_r($user_profile);
} catch(Exception $e){
echo $e->getMessage();
}
}else{
// User not logged in generate the login button or link here
}
Make sure in the above script when user login ffor the first time it reloads the page in other words you need to provide the redirect_uri
https://developers.facebook.com/docs/reference/php/facebook-getLoginUrl/
Also you can use the following api to get the user details
$user_profile = $facebook->api('/'. $fbuser,'GET');
Then add the following below the page. This will check if the user is already logged in it will re-direct to the same page, in other words it will not ask user to login again
<div id="fb-root"></div>
<script type="text/javascript">
window.fbAsyncInit = function()
{
FB.init
({
appId : 'your fb app id',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse XFBML
oauth : true
});
FB.Event.subscribe('auth.login', function()
{
window.location.reload();
});
};
(function()
{
var e = document.createElement('script');
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
</script>
Where do I go from here? This is almost just copy paste from the example provided in the sdk. I don't understand how people can build anything with this API?? How do I open the prompt screen for login etc? Where the heck does Facebook say something about that?
<?php
require 'fb_sdk/src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'APIID',
'secret' => 'SECRET',
));
// Get User ID
$user = $facebook->getUser();
// We may or may not have this data based on whether the user is logged in.
//
// If we have a $user id here, it means we know the user is logged into
// Facebook, but we don't know if the access token is valid. An access
// token is invalid if the user logged out of Facebook.
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
// Permissions requested from the user.
$par = array();
$par['scope'] = 'user_about_me, read_friendlists';
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl($par);
}
?>
You can find information on using the Graph for user authentication here on Facebook Developers.
With $loginUrl = $facebook->getLoginUrl($par); the variable $loginUrl will contain a url to the authentication dialog. Most developers either present this to the user as a link or perform a redirect with javascript - eg:
die('<script>top.location.href = "' . $loginUrl . '"</script>');
The other alternative is to use the JavaScript SDK with XFBML to authenticate (if you have cookies enable with both SDKs they will share session data) - example from here:
<?php
require 'php-sdk/src/facebook.php';
$facebook = new Facebook(array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
));
// See if there is a user from a cookie
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
$user = null;
}
}
?>
<!DOCTYPE html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<body>
<?php if ($user_profile) { ?>
Your user profile is
<pre>
<?php print htmlspecialchars(print_r($user_profile, true)) ?>
</pre>
<?php } else { ?>
<fb:login-button></fb:login-button>
<?php } ?>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId: '<?php echo $facebook->getAppID() ?>',
cookie: true,
xfbml: true,
oauth: true
});
FB.Event.subscribe('auth.login', function(response) {
window.location.reload();
});
FB.Event.subscribe('auth.logout', function(response) {
window.location.reload();
});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
</body>
</html>
You can also login purely with JavaScript using FB.Login:
FB.login(function(response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
FB.logout(function(response) {
console.log('Logged out.');
});
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, {scope: 'user_about_me, read_friendlists'});
It is mentioned in the comment :
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl($par);
}
SDK will take care of that, you need not worry about it.
The user details are there in $user_profile
do a echo"<pre>"; print_r($user_profile); echo"</pre>"; and you will get it.
I am using codeigniter on my site and I use facebook login to login but I have a problem.
->getUser does not return any data when I try my normal codeigniter project. But, in the new folder which is not related my project I try to login from example.php which comes from facebook sdk it works well.
I have checked everything (autoloads, config, etc.)
I think my problem is about sessions.
Thanks for your help.
I suggest that you use the new version of PHP SDK for the Facebook API. I had the same problem with version 3.0.1, that is why I use the previews version 2.1.2 which works just fine.
Unfortunately I don't have time to play with the new version (3.0.1) but there is a very simple example with version 2.1.2:
Config
/* application/config/autoload.php */
$autoload['libraries'] = array('template', 'session', 'facebook');
Library
/* application/libraries/Facebook.php */
require_once("Facebook/2.1.2/facebook.php");
class CI_Facebook extends Facebook {}
Template
/* application/views/template.php */
$facebook = new Facebook(array(
'appId' => 'xxxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'cookie' => true
));
$session = $facebook->getSession();
$me = null;
// Session based API call.
if ($session) {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
}
}
// login or logout url will be needed depending on current user state.
if ($me) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
?>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '<?php echo $facebook->getAppId(); ?>',
session : <?php echo json_encode($session); ?>,
cookie : true,
xfbml : true
});
// whenever the user logs in, we refresh the page
FB.Event.subscribe('auth.login', function() {
window.location.reload();
});
};
(function() {
var e = document.createElement('script');
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
</script>
I'm authenticating via PHP:
// the php facebook api downloaded at step 3
require_once("facebook-client/facebook.php");
// start facebook api with the codes defined in step 1.
$fb=new Facebook( 'XXXXXXXXXXXXXXXXXXXX' , 'a3eaa49141ed38e230240e1b6368254a' );
$fb_user=$fb->get_loggedin_user();
var_dump($fb_user);
And the session is created in PHP. I want to use it with facebook javascript client library from here on out. How do I do this?
With this you can promote a session from PHP to JavaScript and from JavaScript to PHP using the Facebook->setSession() function
<?php
require 'facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => $appId,
'secret' => $secret,
'cookie' => true,
));
$_SESSION['facebook'] = $facebook;
// We may or may not have this data based on a $_GET or $_COOKIE based session.
//
// If we get a session here, it means we found a correctly signed session using
// the Application Secret only Facebook and the Application know. We dont know
// if it is still valid until we make an API call using the session. A session
// can become invalid if it has already expired (should not be getting the
// session back in this case) or if the user logged out of Facebook.
$session = $facebook->getSession();
$me = null;
// Session based API call.
if ($session) {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
} catch (FacebookApiException $e) {
//error_log($e);
}
}else{
//pass in json object of FB._session and convert it to array
$session = json_decode(stripslashes($_POST['session']));
$session = (array) $session;
if($session)
$facebook->setSession($session);
}
?>
var constant = {};
constant.session = <?php echo json_encode($session); ?>;
window.fbAsyncInit = function() {
FB.init({
appId : '<?php echo $facebook->getAppId(); ?>',
session : constant.session, // don't refetch the session when PHP already has it
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
if(!FB._session)
stream.load();
else
jwpage.getAlbums();
// whenever the user logs in, we refresh the stream
FB.Event.subscribe('auth.login', function() {
jwpage.getAlbums();
});
};
(function() {
var e = document.createElement('script');
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
</script>