Facebook getUser() function returning user ID after logout - facebook

I'm developing using the Facebook PHP SDK.
I wanted to make it so that when the user logs out of Facebook, they will automatically be logged out of my website too.
I am using the following code to detect the session, using the session cookie:
$facebook->getUser();
For some reason, the getUser() function still returns the user's Facebook ID, even after they have logged out of Facebook on their website.
Am I to detect the session first using another Function?
On the official documentation example here, is the following excerpt from their comments:
// 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.
This lead me to believe that the session cookie for Facebook would become unset upon Facebook logout?
Kind Regards,
Luke

I have the same issue!
The FB PHP SDK saves those things into the $_SESSION!
You can delete them like this when your user clicks logout:
$_SESSION['fb_'.APP_ID.'_user_id'] = '';
$_SESSION['fb_'.APP_ID.'_access_token'] = '';
Although this is not the final solution, it works for now.
I appreciate comments and solutions on that!

I want to give an alternative, in a way you don't have to handle session stuff. Although, I must warn you this is slower than cleaning up the session, because it relies on a new request. What we're doing in the code below is to check on Facebook if the token is still valid. Here it's:
try {
$facebook->api('/me','GET');
$logged = true;
} catch(FacebookApiException $e) {
$logged = false;
}
In my case, I was doing everything using the JavaScript SDK, so I couldn't clean session on logout. But in my landing page, I was needing a work around to check it before send the response back.
If you're facing something like this, definitely a good solution.

The problem seems to be in php-sdk in basefacebook.php at line 567
protected function getSignedRequestCookieName() {
return 'fbsr'.$this->getAppId();}
This method returns the name of the cookie the sdk is looking for. However, javascript-sdk uses 'fbs_' prefix. Change this to 'fbs_' and it works fine.
return 'fbs'.$this->getAppId();}

$facebook->destroySession();

To destroy the session you can also use:
$facebook->destroySession();

Related

Facebook PHP SDK usage stand alone - how do the Facebook sessions/cookies work?

I'm utilizing the Facebook PHP SDK on its own. I do not want to use the JS SDK at all.
Because getUser(); from the SDK can return a user id even if the user is not logged in, I have opted for using a try/catch statement to check if the user is logged in.
try
{
$me = $CI->facebook->api('/me');
$CI->our_fb['is_fb']='YES';
echo "hello";
}
catch(FacebookApiException $e)
{
echo "catch";
}
This statement is included in the global include file of all of my files (for simplicity).
So, depending on the situation, I generate a Facebook login URL. The expected functionality is that the user logins to Facebook, authorises the app, is returned to the redirect URI set in the login URL at which point the try statement will execute, and $CI->our_fb['is_fb'] will be set.
This is however not happening.
If the user is already logged into Facebook and the app is authorised, it works perfectly. SUCCESS
If the user is not logged into Facebook, once redirected the variable is not set. FAILURE
If the user is logged in but the app is NOT authorised after redirect the variable is not set. FAILURE.
In the latter two cases if you simply refresh the page, the variable is set - SUCCESS. Refreshing the page is however unnecessary/pointless extra effort.
My problem is that if you need to login to FB/or authorise the app e.g the first time you login with FB, you have an additional unneeded refresh, and I don't know why.
I suspect it is something to do with the cookie/session? Which saves the access token that I assume is returned/passed to the SDK automatically not being set at the same time?
Anyone got any ideas?
If you're having an app on facebook (tab or canvas). PHP SDK only get the User ID on initial loading of a page because a signed_request is sent with the request to your app.
But, when the app refreshes, the signed_request is lost (as it's facebook who send it).
So, in this case, you can append the signed_request to every URLs your use in your app - but that's really not optimal as the signed_request won't be regenarated - neither refreshed.
Your only real option is to rely on the JS SDK to set cookie correctly and allow getUser to work as expected. This is required because you're considered as a third-party app in Facebook (being in an iframe) and most browser will block you from setting cookies - so you need a work around handled by the JS SDK for you. You can search for cross-domain cookies or third-party cookie for explanation about the workarounds, but these workaround only work via JS scripting and iframe management.
Also, be sure to setup the JS SDK correctly: channel file, cookie allowed, and send P3P headers (for IE).
You can also check this related question: A proper approach to FB auth
About website, the same mostly stays (but you have no signed_request). At this point, seriously consider using the JS SDK as it's way easier. Or else, you can make sure your app flow follow these guidelines: https://developers.facebook.com/docs/concepts/login/login-architecture/
The way I am seeing this is, you are trying to avoid that refresh if the user is not logged in and precedes to log in after the page has initially loaded.
So what you can do is make an ajax request to another page on your site, say for example id.php, which just loads the php sdk and echo $userid; and then you can grab the user id after login without the refresh.
Basically the cookie is used to save the signed request and session is used to save 'state', 'code', 'access_token', 'user_id'. If the above are present PHP SDK uses them, no matter if they are valid or not.
I think your problem lies in the CODE sent by facebook. Specifically these lines in base_facebook.php:
if ($code && $code != $this->getPersistentData('code')) {
$access_token = $this->getAccessTokenFromCode($code);
...
protected function getAccessTokenFromCode($code, $redirect_uri = null) {
if (empty($code)) {
return false;
}
if ($redirect_uri === null) {
$redirect_uri = $this->getCurrentUrl();
}
...
Because CODE is issued for specific url sometimes there is such situation: Visitor arrives on www.example.com. He givies permissions and is redirected to example.com/login. But the code is not valid there, so the getUserAccessToken returns false. When you refresh the page you get same urls and everything's fine.
You're on the right track of not using getUser() because as I wrote above it's taken from the session if available.

Facebook authentication with codeigniter (active access token must...)

I sign in with FB fine if I directly create a page at domain.com/someurl.php
The moment I copy the same code (inc html) into a view file with codeigniter and go to domain.com/login/someurl.html it doesn't work. By it doesn't work I mean, I get an exception if i try to access /me after signing into facebook.
The message reads "An active access token must be used to query information about the current user"...
In my controller i have my index function and all it does is load the view with the facebook login code.
I thought I may be doing something wrong but I copied the sample.php from the facebook sdk and paste it into the view file and the same thing happens. If i copy the sample code into the file at someurl.php it then works as expected...given the situation I suspected it may be something to do with codeigniter and possibly some config option I have that causes that behaviour...
I've been looking up the error for a while now and have found a few resources:
http://benbiddington.wordpress.com/2010/04/23/facebook-graph-api-getting-access-tokens/
Facebook access_token invalid?
Facebook authentication issue
https://github.com/facebook/php-sdk/wiki/AccessToken
but none of the suggested fixes have worked.
Right from the sample:
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'APPID',
'secret' => 'SHHHH',
));
// 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;
}
}
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
It doesn't work in the view and I'm stumped as to why or why none of the fixes or "precautions" such as not using type or ensuring the redirect url is the same etc, work.
EDIT:
I'm trying to avoid using domain.com/somefile.php and instead use a view file like every other page...
The issue has cropped up in other places such as the Elliot Houghin fb/CI library.
I found a solution documented in a tutorial here:
http://www.dannyherran.com/2011/02/facebook-php-sdk-and-codeigniter-for-basic-user-authentication/
The problem could be cause from one of several issues pointed out on a an issue on Elliot's github repo. I tried many of the suggested "fixes" but the one that seemed to help was not using the facebook instance as a class property. After trying the tutorial at the above link I tried a fresh install of CI again and created a facebook instance inside the function, the API calls with the FB SDK then worked and had no problems so far.
Bug report with suggested fixes #
https://github.com/elliothaughin/codeigniter-facebook/issues/5

Clear all Facebook profile fields and manually fill out the registration form?

You know how users can clear the pre-populated form and revert to normal registration?
I'm developing an iframe registration app and when the user clears the form fields, it looks like the signed_request is still valid (if upon load the user was logged into facebook).
Anyone know how we are supposed to know if the user is really using FB info or registration info? I previously thought the session would tell us but my session is still valid after the
user hits "clear form".
// Check to make sure we have a signed_request object, if not, redirect to home
var sreq = Request.Form["signed_request"];
if (string.IsNullOrEmpty(sreq))
{
Response.Redirect(WebConstants.SiteConstants.Home);
}
var app = new FacebookApp();
WHy is app.UserId still populated if the user clears the FORM!
How do I detect that we really want to integrate with FB or not ?
thanks!
I agree about the authentication vs registration but I think the Facebook API is not clearing the authentication cookie correctly because it is still valid if you clear the form or logout (i'm using iFrame registration), so I guess I'm looking for a best practice since when I get the signed-request, the id is the authenticated user so the only work-around I have right now is to check for String.IsEmptyOrNull( on the password field) - which tells me that this user did not use facebook registration). I think this is a hack but if anyone knows the "proper" way to take a signed request and convert it to an object please comment on my approach. It is kinda amazing that we still have to write a ton of code for what should be a straight forward approach to getting what we need. I've seen tons of complaints about FB development and they are mostly true - the Google API is not this frustrating and FB makes it almost impossible to test different environments as well (not to mention the famous cookie problems with localhost).
Problem : App.UserId is still the authenticated user after clearing the iframe form or logging out of FB - go figure.
Solution : check the presense of password field - this tells us that we have a non-fb registration going on....
C#.NET for all the minority out there.
// Check to make sure we have a signed_request object, if not, redirect to home var sreq = Request.Form["signed_request"]; if (string.IsNullOrEmpty(sreq)) { Response.Redirect(WebConstants.SiteConstants.Home); }
JObject meObject = null;
var app = new FacebookApp();
if (app.SignedRequest != null)
{
meObject = JObject.Parse(app.SignedRequest.Dictionary["registration"].ToString());
// Access meObject
JavaScriptSerializer ser = new JavaScriptSerializer();
fbReg = ser.Deserialize<FBRegistration>(meObject.ToString());
if (fbReg != null)
{
// 02 Feb 2011 - MCS - bug in facebook API, does not delete cookie if logout of FB
// We check to see if we have password - then - we know we can check the UserId
if (String.IsNullOrEmpty(fbReg.password))
{
// FB Registration
FacebookUserId = app.UserId;
}
else
{
FacebookUserId = 0;
// Non FB Registration
Registration and authentication are two completely different things. Just because the user "clears" a form does not log them out of facebook. The C# SDK is just detecting if a signed_request exists and is valid.

Facebook Oauth Logout

I have an application that integrates with Facebook using Oauth 2.
I can authorize with FB and query their REST and Graph APIs perfectly well, but when I authorize an active browser session is created with FB. I can then log-out of my application just fine, but the session with FB persists, so if anyone else uses the browser they will see the previous users FB account (unless the previous user manually logs out of FB also).
The steps I take to authorize are:
Call [LINK: graph.facebook.com/oauth/authorize?client_id...]
This step opens a Facebook login/connect window if the user's browser doesn't already have an active FB session. Once they log-in to facebook they redirect to my site with a code I can exchange for an oauth token.
Call [LINK: graph.facebook.com/oauth/access_token?client_id..] with the code from (1)
Now I have an Oauth Token, and the user's browser is logged into my site, and into FB.
I call a bunch of APIs to do stuff: i.e. [LINK: graph.facebook.com/me?access_token=..]
Lets say my user wants to log out of my site. The FB terms and conditions demand that I perform Single Sign Off, so when the user logs out of my site, they also are logged out of Facebook. There are arguments that this is a bit daft, but I'm happy to comply if there is any way of actually achieving that.
I have seen suggestions that:
A. I use the Javascript API to logout: FB.Connect.logout(). Well I tried using that, but it didn't work, and I'm not sure exactly how it could, as I don't use the Javascript API in any way on my site. The session isn't maintained or created by the Javascript API so I'm not sure how it's supposed to expire it either.
B. Use [LINK: facebook.com/logout.php]. This was suggested by an admin in the Facebook forums some time ago. The example given related to the old way of getting FB sessions (non-oauth) so I don't think I can apply it in my case.
C. Use the old REST api expireSession or revokeAuthorization. I tried both of these and while they do expire the Oauth token they don't invalidate the session that the browser is currently using so it has no effect, the user is not logged out of Facebook.
I'm really at a bit of a loose end, the Facebook documentation is patchy, ambiguous and pretty poor. The support on the forums is non-existant, at the moment I can't even log in to the facebook forum, and aside from that, their own FB Connect integration doesn't even work on the forum itself. Doesn't inspire much confidence.
Ta for any help you can offer.
Derek
ps. Had to change HTTPS to LINK, not enough karma to post links which is probably fair enough.
I was having the same problem. I also login using oauth (I am using RubyOnRails), but for logout, I do it with JavaScript using a link like this:
Logout
This first calls the onclick function and performs a logout on facebook, and then the normal /logout function of my site is called.
Though I would prefer a serverside solution as well, but at least it does what I want, it logs me out on both sites.
I am also quite new to the Facebook integration stuff and played around the first time with it, but my general feeling is that the documentation is pretty spread all over the place with lots of outdated stuff.
This works as of now - and is documented on facebook's site # http://developers.facebook.com/docs/authentication/. Not sure how recently it was added to the documentation, pretty sure it wasn't there when I checked Feb-2012
You can programmatically log the user our of Facebook by redirecting
the user to
https://www.facebook.com/logout.php?next=YOUR_REDIRECT_URL&access_token=USER_ACCESS_TOKEN
This solution no longer works with FaceBook's current API (seems it was unintended to begin with)
http://m.facebook.com/logout.php?confirm=1&next=http://yoursitename.com;
Try to give this link on you signout link or button where "yoursitename.com"
is where u want to redirect back after signout may be ur home page.
It works..
I can programmatically log user out Facebook by redirecting user to
https://www.facebook.com/logout.php?next=YOUR_REDIRECT_URL&access_token=USER_ACCESS_TOKEN
The URL supplied in the next parameter must be a URL with the same base domain as your application as defined in your app's settings.
More details: https://developers.facebook.com/docs/authentication
You can do this with the access_token:
$access_array = split("\|", $access_token);
$session_key = $access_array[1];
You can use that $session key in the PHP SDK to generate a functional logout URL.
$logoutUrl = $facebook->getLogoutUrl(array('next' => $logoutUrl, 'session_key' => $session_key));
This ends the browser's facebook session.
With PHP I'm doing:
logout.
if(isset($_GET['action']) && $_GET['action'] === 'logout'){
$facebook->destroySession();
header(WHERE YOU WANT TO REDIRECT TO);
exit();
}
Works and is nice and easy am just trying to find a logout button graphic now!
Here's an alternative to the accepted answer that works in the current (2.12) version of the API.
Logout
<script>
FB.init({
appId: '{your-app-id}',
cookie: true,
xfbml: true,
version: 'v2.12'
});
function logoutFromFacebookAndRedirect(redirectUrl) {
FB.getLoginStatus(function (response) {
if (response.status == 'connected')
FB.logout(function (response) {
window.location.href = redirectUrl;
});
else
window.location.href = redirectUrl;
});
}
</script>
the mobile solution suggested by Sumit works perfectly for AS3 Air:
html.location = "http://m.facebook.com/logout.php?confirm=1&next=http://yoursitename.com"
For Python developers that want to log user out straight from the backend
At the moment I'm writing this, the trick with m.facebook.com no longer works (at least for me) and user is redirected to the mobile FB login page which obviously is not good for UX.
Fortunately, FB PHP SDK has a semi-documented solution (in case the link doesn't lead to getLogoutUrl() function, just search look for it on that page). This is also mentioned in at least one other on StackOverflow: Facebook php SDK getLogoutUrl() problem.
BTW I've just noticed that Zach Greenberg got it right in this question, but I'm adding my answer as a summary for Python developers.
A note for Christoph's answer:
Facebook Oauth Logout
The logout function requires a callback function to be specified and will fail without
it, at least on Firefox. Chrome works without the callback.
FB.logout(function(response) {});
#Christoph: just adding someting . i dont think so this is a correct way.to logout at both places at the same time.(Logout).
Just add id to the anchor tag . <a id='fbLogOut' href="/logout" onclick="FB.logout();">Logout</a>
$(document).ready(function(){
$('#fbLogOut').click(function(e){
e.preventDefault();
FB.logout(function(response) {
// user is now logged out
var url = $(this).attr('href');
window.location= url;
});
});});
Update: This solution works and just a call to 'FB.logout()' doesn't work because browser wants a user interaction to actually call this function, so that it knows - it is a user not a script.
Logout
it's simple just type : $facebook->setSession(null); for logout

facebook api - How to expire current session?

//file test.php
require_once 'config.php';
if($fb->get_loggedin_user())
{
// step1 do something
//step2 expire session
}
else
{
//FB coonect login button
}
I need to expire session after i am done with the step1 in the above code. But $facebook->get_loggedin_user() always returns a user id and never goes into else part.
I tried $fb->clear_cookie_state(); $fb->api_client->user=0; $fb->api_client->session_key=null; $fb->logout('index.php');
Nothing is seems to be working. please help. How can i make him log out??
There is currently no way to do this through Facebook's "RESTful API" which is what the PHP client library interfaces with. You can, however, accomplish this with Facebook's "JavaScript API" which includes the functions FB.Connect.logout() and FB.Connect.logoutAndRedirect(url). Calling either of these functions on any Facebook canvas page or FB Connect page will expire the user's current Facebook session.