laravel4 hybridauth facebook Authentication failed! Facebook returned an invalid user id - facebook

OK, I'm trying to use Hybridauth with laravel 4. However I seem to be getting the very common when trying to log in with facebook:
Authentication failed! Facebook returned an invalid user id.
I have read all the other posts, and have had no luck, so just hoping someone may be able to help me.
I followed this tutorial: http://www.mrcasual.com/on/coding/laravel4-package-management-with-composer/
And have tried several other configurations to no success.
Here is my config/hybridauth.php
<?php
return array(
"base_url" => "http://myapp.dev/social/auth/",
"providers" => array (
"Facebook" => array (
"enabled" => true,
"keys" => array ( "id" => "****", "secret" => "****" ),
),
),
);
And here is my route:
Route::get('social/{action?}', array("as" => "hybridauth", function($action = "")
{
// check URL segment
if ($action == "auth") {
// process authentication
try {
Hybrid_Endpoint::process();
}
catch (Exception $e) {
// redirect back to http://URL/social/
return Redirect::route('hybridauth');
}
return;
}
try {
// create a HybridAuth object
$socialAuth = new Hybrid_Auth(app_path() . '/config/hybridauth.php');
// authenticate with Facebook
$provider = $socialAuth->authenticate("Facebook");
// fetch user profile
$userProfile = $provider->getUserProfile();
}
catch(Exception $e) {
// exception codes can be found on HybBridAuth's web site
return $e->getMessage();
}
// access user profile data
echo "Connected with: <b>{$provider->id}</b><br />";
echo "As: <b>{$userProfile->displayName}</b><br />";
echo "<pre>" . print_r( $userProfile, true ) . "</pre><br />";
// logout
$provider->logout();
}));
So, when I access "myapp.dev/social" I'm brought to the facebook sign up page everthing seems to work fine, asks me to allow permissions to myadd.dev. After I click OK I am brought to the following URL: http://myapp.ie/social#_=_ where the error is displayed.
Not sure if this is relevant:
Just from observing other sites that in-cooperate a facebook login.. the redirect URL looks something like http://somesite.dev/subdomain/#_=_ . In other words they have a slash before the #=. Is this my problem, how do I fix it?? Very new to hybridauth so any help greatly appreciated thanks.
Oh I do realize that this post is very similar to other posts but I have yet to find a solution.
UPDATE: the exact error: Authentification failed. The user has canceled the authentication or the provider refused the connection.

In base_facebook.php do following
public static $CURL_OPTS = array(
CURLOPT_CONNECTTIMEOUT => 50,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 60,
CURLOPT_USERAGENT => 'facebook-php-3.2',
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
);
protected $trustForwarded = true;
protected $allowSignedRequest = false;

CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false
at modules/hybridauth/Hybrid/thirdparty/Facebook/base_facebook.php:128
solved!

For anyone else this is what worked for me: I reset app secret and now works great. No idea why my first app secret key did not work. Spent a ridiculous amount of time trying to fix this error.

Had this error in the past. Solved by modyfying Hybridauth's code myself.
In thirdparty/Facebook/base_facebook.php make sure $CURL_OPTS array uses:
CURLOPT_SSL_VERIFYPEER => false
In my case I was closing session files for performance improvements so I added:
session_start()
inside Storage.php wherever HA::STORE session var is being updated/unset.
Let me know if it helps.

CURLOPT_SSL_VERIFYPEER => false & resetting my app secret key didn't work for me. I was getting this error because of some conflict with privileges I had previously setup. Removing the app from my facebook account did the trick (under privacy settings -> apps).

REMOVE THE TRAILING SLASH !!! (in config/hybridauth.php)
"base_url" => "http://myapp.dev/social/auth/",
should be
"base_url" => "http://myapp.dev/social/auth",

My case was a little bit more specific, but just in case: Be carefull with redirects!
I had an SSL Certificate installed and a redirect to force the user over https, but when I first configured HybridAuth I didn't took this into account. The facebook request was being redirected over to https causing the $_REQUEST data to be lost in the process.
For me the change was, in Hybrid/config.php:
"base_url" => "http://my-site.com/"
to
"base_url" => "https://my-site.com/"

I was having the same issue (although using HybridAuth on Yii) and turns out my app on Facebook was still in Sandbox mode. No source code changes needed on HybridAuth, just needed to turn off Sandbox Mode for the app and suddenly everything worked. Hope this helps.

This happened to me because my SSL is terminated in AWS's load balancer
Just update the config file in your app/config to include the trustForwarded setting
<?php
return array(
'base_url' => 'http://website.com/oauth/auth',
'providers' => array (
'Facebook' => array (
'enabled' => true,
'keys' => array ( 'id' => 'redacted', 'secret' => 'redacted' ),
'trustForwarded' => true,
),
),
);

I had the exact same error message on a wordpress installation using Hybridauth. To find the problem I set up an isolated test with the Facebook PHP SDK (which Hybridauth uses) just to find out that curl_exec was not enabled on my host. Happily, an easy fix.
If you are on apache open you php.ini and delete curl_exec from this line:
disable_functions = curl_exec
Reload your apache configuration and voila :)
Hope this will help somebody.

Related

Endless redirect loop in Facebook canvas application

I have tried to search this, but have found no answers. I have [had] a working application on Facebook up until yesterday, then all hell broke loose and it simply doesn't come up. Please keep in mind, nothing changed on my end. The application has been running for over a year with no problems.
Yesterday, I accessed the application like normal and got an additional permission request for access to my friends list. Strange, again because I have made no changes to the code or the configuration on FB. I accepted the request and now instead of the application coming up, it simply goes into an endless oauth login redirect loop. In fact it doesn't even look like it ever calls my application url as I cannot debug it (it never breaks on the code)
I guess my question is, does anyone know of something changing recently on FB to cause this?
The application can be found at: https://apps.facebook.com/myworkoutlog
And as I wrote this, the app came up, but after closing the browser and starting again, back into the endless loop. Any help would be great. If you need additional information, please just ask.
Edit:
I finally got it into debug and it breaks when I try to get an access_token using a verification code: (OAuthException - #100) Invalid verification code format.
Try this it works for me ;)
include_once "facebook.php";
$facebook = new Facebook(array(
'appId' => 'xxxxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxxxxxxx',
'cookie' => true
));
$fb_user = $facebook->getUser();
if($fb_user){
if(isset($_GET['code']) && isset($fb_user)){
$fbAppNs = 'appOnFacebookNameSpace';
$facebookAppUrl = 'https://apps.facebook.com/'.$fbAppNs;
header("Location: " . $facebookAppUrl);
exit;
}
try{
$user_profile = $facebook->api('/me');
$smarty->assign('name', $user_profile['first_name'].' '.$user_profile['last_name']);
$smarty->assign('email', $user_profile['email']);
}catch(FacebookApiException $e){
error_log($e);
$user = NULL;
}
}else{
$loginData = array(
'scope' => 'email,publish_stream',
'canvas' => 1,
'fbconnect' => 0,
'redirect_uri' => $siteConfigs['WEBSITE_URL'].'fblead/'
);
$loginUrl = $facebook->getLoginUrl($loginData);
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
exit;
}

How to integrate CakePHP-app to Facebook canvas

I have problems integrating CakePHP-app (2.3.8) to Facebook canvas. When I load the app-page in Facebook, the answer is:
The request has been black-holed
Error: The requested address '/?fb_source=search&ref=ts&fref=ts' was not found on this server.
I have defined in Facebook's app settings that my Canvas secure URL is:
https://facebook.mydomain.com/
So the page is found by Facebook. (actually if the CakePHP's tmp/ directory is not writable, the Facebook's app-page displays the error message about that -> so the URL is at least correct)
I have used Facebook PHP-SDK for integrating to Facebook. My page works as a standalone page, but integrating to Facebook Canvas is the problem.
Here is my Config/facebook.php
$config = array(
'Facebook' => array(
'appId' => '***********',
'secret' => '**********************'
)
);
And here is my Controller for Facebook related stuff:
public function login() {
Configure::load('facebook');
$appId = Configure::read('Facebook.appId');
$app_secret = Configure::read('Facebook.secret');
$facebook = new Facebook(array(
'appId' => $appId,
'secret'=> $app_secret
));
$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'user_birthday,user_location',
'redirect_uri' => BASE_URL . 'books/facebook_connect',
'display' => 'popup'
));
$this->redirect($loginUrl);
}
public function facebook_connect() {
Configure::load('facebook');
$appId = Configure::read('Facebook.appId');
$app_secret = Configure::read('Facebook.secret');
$facebook = new Facebook(array(
'appId' => $appId,
'secret'=> $app_secret
));
$user = $facebook->getUser();
// And the rest of this function is only for saving the authenticated user to the database
All the tutorials I have found are pretty straightforward and they make it look so easy to integrate to Facebook canvas. I have not succeeded even in getting the most simple "hello world"-page with only index.php and facebook php-sdk to work. I have tried also with cookies set to true, but that didn't help either.
This is pretty broad question and it must be hard to imagine what could be wrong in my case, but if you can find out anything or had suffered from similar errors, please share your knowledge.
UPDATE ! :
Here is var_dump($this->params); from booksController.php:
object(CakeRequest)#6 (9) {
["params"]=>
array(5) {
["plugin"]=>
NULL
["controller"]=>
string(5) "books"
["action"]=>
string(5) "index"
["named"]=>
array(0) {
}
["pass"]=>
array(0) {
}
}
["data"]=>
array(2) {
["signed_request"]=>
string(514) "//here is a very long string hash"
["locale"]=>
string(5) "en_GB"
}
(I didn't paste the whole var_dump() here because lots of unnecessary information)
So what I understood is that I need to somehow validate that signed_request from Facebook to get my website working in Facebook canvas? I just don't have any clue how to do that... I have implemented "my own" admin authentication system with Auth-components. I know that I would need to fix something from there, but I somehow don't know where to start. Too much moving parts...
Is the approach presented in the answer below correct one? At least it fixed that problem, but mine it didn't. What I mean is, what is the key element in that answer which I can transfer to my code? Or if I only get a full picture, I would find out myself the answer...
SECOND UPDATE ! :
I unset($this->request->data['signed_request']) and then $this->Security->csrfCheck = false... didn't work. What I'm missing?
The "blackhole" is due to your Security Component. I believe your issue has been resolved at this question/answer: CakePHP and Facebook with Security Component turned on

SoundCloud API: Tweeting on upload and disable comments

The following PHP code uploads a new track to SoundCloud successfully, but the tweet is not sent.
Is there something I need to have in there as well in order to do this?
$track = $soundcloud->post('tracks',
array(
'track[asset_data]' => '#audio.mp3',
'track[title]' => "my audio",
'track[description]' => "Updated: " . date('l jS F Y h:i:s A'),
'track[sharing]' => 'public',
'track[shared_to][connections][][id]' => '123',
'track[sharing_note]' => 'Have a listen to'
));
Also I'd like to be able to disable comments on the audio I upload, but I wasn't sure what the parameter for that would be too?
Thanks!
dB
I'm unable the repro the sharing problem. Please note that sometimes sharing on other social networks doesn't happen right away. Are you still having trouble? Here's the code I used:
<?php
require_once 'Services/Soundcloud.php';
$client = new Services_Soundcloud("foo", "bar");
$client->setAccessToken('ACCESS_TOKEN');
$track = $client->post('tracks', array(
'track[title]' => 'Foooo',
'track[asset_data]' => '#/Users/paul/audio.wav',
'track[sharing]' => 'public',
'track[shared_to][connections][][id]' => 'CONNECTION_ID',
'track[sharing_note]' => 'Check it out'
));
print_r($track);
Also verify that your CONNECTION_ID is correct. Some code to get a list of connections so you can verify the id:
<?php
require_once 'Services/Soundcloud.php';
$client = new Services_Soundcloud("foo", "bar");
$client->setAccessToken('ACCESS_TOKEN');
print_r(json_decode($client->get('me/connections')));
Unfortunately there's no way currently to disable comments via the API. I'll file a bug and see about getting this fixed.
Hope that helps!

facebook php sdk server An error occurred. Please try again later

I'm asking you for help, because I can't understand what I'm doing wrong. I was trying to make secondary user authentication by Facebook for my application.
I had done everything according to this blog entry:
http://thinkdiff.net/facebook/php-sdk-3-0-graph-api-base-facebook-connect-tutorial/
and once verification went fine and since another time I have error:
"An error occurred. Please try again later."
I can't even get cause of error or any message. Everything seems to be OK. But I can't get through verification. When i use FB loginUrl i redirects me to error.
This is my FB code:
var $fbconfig = array(
'appId' => '1234567890',
'secret' => '12345678901234567890',
'baseurl' => "http://xxxx.xx",
'fbLoginSuccess' => "http://xxxx.xx/xx/xxxx",
'cookie' => true
);
$facebook = new Facebook(
array(
'appId' => $fbconfig['appId'],
'secret' => $fbconfig['secret'],
'cookie' => $fbconfig['cookie'],
)
);
$userFB = $facebook->getUser();
if ($userFB) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'email',
'redirect_uri' => $fbconfig['fbLoginSuccess']
)
);
}
I had found a way to receive answer through redirect_uri with err_msg variable. And then found a solution here: http://developers.facebook.com/bugs/112163982233944
I had found a way to receive answer through redirect_uri with err_msg variable. And then found a solution here: http://developers.facebook.com/bugs/112163982233944. I didn't notice that I had turned sandBox mode "on"
I'm sure everybody's situation is a bit different. But for me, I was using php-sdk and got the message when I clicked the "Login to Facebook" link from the example script.
The issue resolved after I updated the 'appID' and 'secret' and then pushed the change back to heroku (i.e. - 'git push heroku master')
The key is not to forget to push the changes back to heroku master. Very easy to overlook if you're use to testing on localhost.
Hope this helps.

Linkedin OAuth and Zend retrieving Acces Token returns 'Error in HTTP request'

Answer + new question
I found out that the code below works just fine on a LIVE server. LinkedIN blocked all requests from localhost.
That established; Does anybody know how to test an application from localhost with LinkedIN OAuth? Because doing this on a live server sucks!
Old Question
I'm trying to connect with Zend_OAuth to LinkedIN. This code used to work, but now it returns an error in http request while I'm trying to retrieve an access token.
Tried checking the LinkedIN api, but the code still seems valid. Tried several scripts but all with the same result.
The config is setup in the preDispatch of my controller
$this->configLinkedin = array(
'version' => '1.0',
'siteUrl' => 'http://'.$_SERVER['HTTP_HOST'].$this->view->baseUrl(false).'/news/index/connectlinkedin',
'callbackUrl' => 'http://'.$_SERVER['HTTP_HOST'].$this->view->baseUrl(false).'/news/index/connectlinkedin',
'requestTokenUrl' => 'https://api.linkedin.com/uas/oauth/requestToken',
'userAuthorisationUrl' => 'https://api.linkedin.com/uas/oauth/authorize',
'accessTokenUrl' => 'https://api.linkedin.com/uas/oauth/accessToken',
'consumerKey' => 'XXX',
'consumerSecret' => 'XXX'
);
And the code in the action to connect to linkedIN is
$this->consumer = new Zend_Oauth_Consumer($this->configLinkedin);
if(!empty($_GET) && isset($_SESSION['LINKEDIN_REQUEST_TOKEN']))
{
$token = $this->consumer->getAccessToken($_GET, unserialize($_SESSION['LINKEDIN_REQUEST_TOKEN']));
// Use HTTP Client with built-in OAuth request handling
$client = $token->getHttpClient($this->configLinkedin);
// Set LinkedIn URI
$client->setUri('https://api.linkedin.com/v1/people/~:(id,first-name,last-name,picture-url)');
// Set Method (GET, POST or PUT)
$client->setMethod(Zend_Http_Client::GET);
// Get Request Response
$response = $client->request();
$this->NewsService->TokenSocialMedia(
$token,
'linkedin',
serialize($response->getBody())
);
$_SESSION['LINKEDIN_REQUEST_TOKEN'] = null;
$this->_helper->flashMessenger(array('message' => $this->view->translate('The CMS is successfully connected to your linkedin account'), 'status' => 'success'));
$this->_helper->redirector('settings#settingSocial', 'index');
}
else
{
$token = $this->consumer->getRequestToken();
$_SESSION['LINKEDIN_REQUEST_TOKEN'] = serialize($token);
$this->consumer->redirect();
}
What am I missing or doing wrong? I use a similair setup for Twitter and that works fine.
UPDATE 20 September 211
I found out that this rule is returning the error:
$token = $this->consumer->getRequestToken();
I'm still clueless why, and reading the linkedin api doesn't help a bit. Will keep you posted.
I got similar problem and after adding openssl extension it was solved
try adding to php.ini this line:
extension=php_openssl.dll
I got the same issue, try to turn off ssl before asking the new consumer :
$httpConfig = array(
'adapter' => 'Zend\Http\Client\Adapter\Socket',
'sslverifypeer' => false
);
$httpClient = new HTTPClient(null, $httpConfig);
OAuth::setHttpClient($httpClient);