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

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

Related

Firefox and Chrome gives "too many redirects" error on the following Facebook Connect implementation

// GET "giris-yap/facebook"
public function action_facebook_index()
{
$facebook = IoC::resolve('facebook-sdk');
$user = $facebook->getUser();
if($user)
{
$profile = $facebook->api('/me');
return View::make('home.login-facebook')
->with('message_area', null)
->with('username', $profile['username']);
}
else
{
return Redirect::to($facebook->getLoginUrl(array('next' => 'http://dugun.dev/giris-yap/facebook')));
}
}
// POST "giris-yap/facebook"
public function action_facebook_process()
{
$facebook = IoC::resolve('facebook-sdk');
$user = $facebook->getUser();
$profile = $facebook->api('/me');
$input = Input::all();
Auth::attempt(array('username' => $profile['username'], 'password' => $input['password']));
if(Auth::check())
return Redirect::to('account');
else
return View::make('home.login-facebook')
->with('message_area', 'Giriş denemesi başarısız.')
->with('username', $profile['username']);
}
The code above works flawlessly on my machine but my friend get's an error on both Chrome and Firefox.
Chrome: Error 310 (net::ERR_TOO_MANY_REDIRECTS): There were too many redirects.
Firefox: Firefox has detected that the server is redirecting the request for this address in a way that will never complete.
It happens on this line:
return Redirect::to($facebook->getLoginUrl(array('next' => 'http://dugun.dev/giris-yap/facebook')));
In theory; I redirect to Facebook, then Facebook redirects back to action_facebook_index(), and it repeats. However, Facebook should not be redirecting it. It should show user the form to give application permissions, then redirect back. That works normally on my personal computer, but my friend is having the issues above.
Is there anything I can do to solve it?
Probably won't fix it but you should separate some of the logic. The part that checks for a logged in Facebook user should be in a Route filter. Then remove the array passed as parameter to the getLoginUrl method (Facebook automatically redirects to the requesting page).
Also your friend might have cookies turned off?
The problem was Facebook Application being in Sanbox mode, so only as the application owner, I had access to the required API's. If someone else made the request, Facebook redirected them back and hence creating an infinite loop.
The issue was solved by closing Sandbox mode on Facebook Application Settings and giving appropriate permissions.

suddenly facebook connect stopped working

A few days ago the facebook connection with our website stopped working all of the sudden, nothing was changed to the code???
Facebook made some changes???
http://www.presbium.sk/vstup-pre-uchadzacov/
require 'facebook-php-sdk/src/facebook.php';
$facebook = new Facebook(array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
));
// Get User ID
$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) {
error_log($e);
$user = null;
}
}
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
enter code here
You can find everything you need there:
http://developers.facebook.com/docs/
For login:
http://developers.facebook.com/docs/authentication/
for Facebook Connect:
http://developers.facebook.com/docs/reference/api/
Facebook Login is not an official Facebook expression. The official term for this is Facebook Authentication. Facebook Connect was the expression used for the server to server technology, back when the Rest API was up to date. Now, you have to use the Graph API to do the same things. You can find the infos about the old Rest API here:
http://developers.facebook.com/docs/reference/rest/
But consider these APIs are deprecated and using them for a new development is probably not a good idea.
There are changes to Facebook's API implemented continuously. Some of them may break your app's functionality. A good way to stay-up-to-date about what changes are happening is to following the Operation Developer Love platform updates. There you can find out about bugs and breaking changes to the API. Go through the latest blog updates to see if there is a change you have missed to implement.
Edit:
You wrote:
I did everything as here github.com/facebook/facebook-php-sdk and befor 1 month it works but now it don´t working
The SDK github examples give you a blue print for a general case. The error is most likely something that's app specific, for example which permissions you ask for. I recommend you really go through all the 'breaking changes' in the blog for the past 3 months and see what it can be. For example, the 'offline access' permission was removed a while ago. If your app still asks for it, the apps expected behaviour may break. There are also new requirements for having a privacy policy that if not met may cut off the app's access to parts of the API. I'm not saying these are the source of issue with your app, they're just examples. Real examples.

Facebook PHP SDK - Have to reauthenticate during new browser session?

Hopefully this should be quick and easy.
session_start();
include("facebook.php");
$facebook = new Facebook(array(
'appId'=>'xxxxx50274xxxxx',
'secret'=>'xxxxxb932d62fbc6287feb18e5exxxxx',
'cookie'=>true
));
$fbuser = $facebook->getUser();
if (empty($fbuser)){
$fbloginurl=$facebook->getLoginURL();
echo "<html><body><a href='$fbloginurl'>Click</a></body></html>
} else {
die("Authenticated");
}
In this example, the first time I click the link to give permissions to the app to access my FB account, everything works fine. I can keep refreshing the page, and I get the "Authenticated" confirmation.
However, every time I restart the browser (starting a new session), it doesn't authenticate the app automatically and I have to click the link again. Of course as soon as I click the link I am immediately redirected back to the source page and presented with the "Authenticated" confirmation.
Is there any way of not having to click the authentication link during new browser sessions and have it authenticate automatically? I need to do this without a PHP Header directive, as I want the first time the user gives permissions to the app to be triggered by a manual click.
My FB login is persistent ("stay logged in" option is checked).
Thanks a lot for any help.
If I am understanding your scenario correctly (this is not an iframe app, correct?), this is all down to losing the website session cookie when the browser is closed. Once that cookie is gone, there is nothing to identify the user to your server-side code and so no way to know if the user has previously authorized your app.
You need to find a way to persistently identify the user, or at least identify that he has already given permissions. The simplest way would probably be to set your own (permanent) cookie once the user has first authenticated. Then whenever the session cookie is lost, check the presence of the permanent cookie and if it's there, do a PHP redirect to Facebook (which will be invisible to the user). If there is no cookie, present the HTML link to the user like you are doing now.
Comparing it to my code, the only difference I see is that I check to see if $fbuser is valid - if it isn't send me to the login screen. I'm also using top.location.href.
// Login or logout url will be needed depending on current user state.
if ($fbuser) {
$logoutUrl = $facebook->getLogoutUrl();
}
else {
$loginUrl = $facebook->getLoginUrl(array('scope' => 'publish_actions', 'canvas' => 1, 'fbconnect' => 0, 'redirect_uri'=>config_item('facebook_url').$pf));
echo "<html><body><script> top.location.href='" . $loginUrl . "'</script></body></html>";
exit(0);
}
Hope that helps.

$facebook->getUser() always returns 0 [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why is Facebook PHP SDK getUser always returning 0?
Am using the following code to authenticate Facebook uses and redirecting them to login page if not logged in or require permission. Problem is getUser() always returns 0 causing the code to get stuck in a redirecting loop. Any ideas?
include_once("facebook.php");
$app_id = 'xxxxxxxxxxxx';
$app_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
// initialize facebook
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
));
$user = $facebook->getUser();
echo $user;
if ($user) {
try {
$fbme = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
else
{
$loginUrl = $facebook->getLoginUrl(array('scope' => 'email'));
header('Location: '.$loginUrl);
}
After days of searching I found that I just wasn't adding a 'code' key value when using the Facebook API. The system needs it in order to validate
When you use the API function $facebook->getLoginUrl(); it takes you to a login-page that (when you authenticate properly) simply returns you to your own website with a code="x" parameter in the navigation bar. So when instantiating the Facebook Object you simply use a get request to nab this piece of information.
when your page reloads the Facebook API, make sure that one of its key values is
'code' => $_GET['code'],
sorted..
Really angry that I had to figure this out myself.. Look at the getLoginUrl() docs here http://developers.facebook.com/docs/reference/php/facebook-getLoginUrl/ and you'll find that nowhere does it specify what it returns, just that it "authorises" the app, whatever the hell that means.
Also on the main page of the PHP API docs found here http://developers.facebook.com/docs/reference/php/, it states that the minimum number of parameters required are an app secret and an appID. If this is the case, then why does adding the code sort my problem?
If I'm talking nonsense, please respond. I like to know the error of my ways :).
This is not a sdk related problem, SDK (3.1) working well. getUser() and PHP-SDK silently fails if _REQUEST like globals dropping by http server if misconfigured. I was using wrong-configured nginx and after tracing code ~3 hours solved this problem via vhost configuration change.

Facebook getUser() function returning user ID after logout

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