Facebook API: redirect_uri - php

I've readeded that FB API have problems with redirect_uri - and i've try to make it work on my framework. Problem is easy, but i haven't found working solution so i think this is right place, and someone help me.
I've creating login link:
$loginUrl = $helper->getLoginUrl( $app_url . 'fb/oauth/' , $permissions );
where $app_url . 'fb/oauth/' looks like this http://domain.com/fb/oauth/
This path is redirected thru htaccess > index.php (routing) > plugins/facebook/facebook-callback.php
And in oauth.php file i've valid code - but i've get error:
Error validating verification code. Please make sure your redirect_uri is identical to the one you used in the OAuth dialog request
Main problem is that i don't want to redirect to domain.com/fb_oauth.php - i prefer to use rewrite/route way to be more pretty. Everything is correct, i've checked slash at the end (because some have problems with that).
I also think that error may be in the way that route redirect to callback file:
if($route->path = 'fb/oauth') {
include $app_path . "plugins/Facebook/facebook-callback.php";
} else {
die("Unknown");
}
Please help me - i don't have other ideas. I prefer to not use direct link to .php, and use my way (my variables are defined before include destination file)
Thank You !
EDIT:
I've also try domain.com/oauth and domain.com/oauth/
same error :-(

Related

Facebook sdk returning errors on requesting tokens [duplicate]

In facebook documantion
require('include/facebook/autoload.php'); //SDK directory
$fb = new Facebook\Facebook([
'app_id' => '***********',
'app_secret' => '***********************'
]);
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email', 'public_profile']; // optional
$loginUrl = $helper->getLoginUrl('http://www.meusite.com.br/login-callback.php', $permissions);
When direct it to the url $loginUrl, the return is:
Facebook SDK returned an error: Cross-site request forgery validation failed. The "state" param from the URL and session do not match
I had the same error.
The problem occurred because I did getLoginUrl(...) before getAccessToken()
So rid of getLoginUrl(...) in redirected URL and code should works.
I had the same issue and for me that error was occurring because I did not put session_start(); in my login.php page code before calling getLoginUrl(..) and also at the top of login-callback.php page.
Just put session_start(); in your "login" page and "login-callback" page and it will work surely just like it is working for me now.
There could be 2 reason for this error:
you didn't call session_start(); before getLoginUrl call
You executed getLoginUrl again in login-callback.php, so state value regenerated and mismatched with the redirected value
Possible Fixes : I used the following configuration settings .
Enable WebAuthLogin under the advanced tab . Provide the url in the WebAuthLogin settins as same as that you provide in $loginUrl ;
For example if you use $loginUrl as https://example.com/ use that same in the WebAuthlogin Url
$loginUrl = $helper->getLoginUrl('https://example.com/', $permissions);
This problem occures also in case that you generate 2 or more login links on the same page (e.g. one for login and other for registration - even both point to the same url, they have just different labels).
Facebook SDK creates/updates $_SESSION[FBRLH_state] for each new generated loginURL. So if there are 2 generated URLs (using $helper->getLoginUrl()) then the $_SESSION[FBRLH_state] is 2-times rewritten and valid only for the last generated URL. Previous login URL becomes invalid. It means that it is not possible to generate 2 valid loginURLs. In case that 2 same URLs are generated then return the first one and avoid call of Facebook SDK for generation of second one.
I had the same problem.
The reason for this error is because --->
When "$helper->getLoginUrl" calls, it create a session variable "FB_State", and this is something to FB uses to match the token. Every-time getLoginUrl calls, it create new state. Then after user authorized and redirect back, if you codes cannot detect this event and re-run "$helper->getLoginUrl", then this error will occur.
The solution ->
refine your coding, stop run "$helper->getLoginUrl" again if authorized.
if you already rerun, then set the session variable for the token to NULL if you have, then User can re-authorize again.
when user tries re-authorize, they can remove the authorized APP once or you need to generate new link with "$helper->getReRequestUrl"
Yet, token has be called by "getAccessToken()" before the "$helper->getLoginUrl" or "$helper->getReRequestUrl" runs.
Good Luck!!!!!
Finally, looking into FB code, I discovered that the problem "Cross-site request forgery validation failed. Required param “state” missing" and similars are caused by PHP variable $_SESSION['FBRLH_state'] that for some "strange" reason when FB call the login-callback file.
To solve it I store this variable "FBRLH_state" AFTER the call of function $helper->getLoginUrl(...). Is very important to do only after the call of this function due to is inside this function when the variable $_SESSION['FBRLH_state'] is populated.
Below an example of my code in the login.php:
$uri=$helper->getLoginUrl($uri, $permissions);
foreach ($_SESSION as $k=>$v) {
if(strpos($k, "FBRLH_")!==FALSE) {
if(!setcookie($k, $v)) {
//what??
} else {
$_COOKIE[$k]=$v;
}
}
}
var_dump($_COOKIE);
And in the login-callback.php before calling all FB code:
foreach ($_COOKIE as $k=>$v) {
if(strpos($k, "FBRLH_")!==FALSE) {
$_SESSION[$k]=$v;
}
}
Last, but not least, remember also to include code for PHP session so..
if(!session_id()) {
session_start();
}
...
...
...
...
<?php session_write_close() ?>
I hope this response can help you to save 8-10 hours of work :)
Bye, Alex.
This issue was a bit confusing for me, because I had to change a line at the facebook src file:
src/Facebook/Helpers/FacebookRedirectLoginHelper.php
at the function: "validateCsrf" like this:
if ($result !== 0) {
throw new FacebookSDKException('Cross-site request forgery validation failed. The "state" param from the URL and session do not match.');
}
And change it into:
if ($result === 0) {
throw new FacebookSDKException('Cross-site request forgery validation failed. The "state" param from the URL and session do not match.');
}
I don't know if this makes a violation to the facebook SDK security, so I truly opened to any exlanation or recommendation for this answer.
You may also make the following changes at the facebook app manager:
add your site and callback-url into your facebook app account at:
setting->advanced:Valid OAuth redirect URIs
Don't forget to add another url with slash (/) at the end of each url and check all 4 checkboxes at Client OAuth Settings.
I had the same error. Are you using 1 file or 2? I was trying to get by using 1 file but my error was resolved when I split into login.php & fb-callback.php as the documentation recommended. My sessions were being re-written so the state was never saved properly.
Good luck!
Happens when the session in missing a needed variable.
might be caused by several things.
In my case I left the "www" out of the callback URL
You could actually be parsing the data from another domain... for example:
website.com is different from www .website.com
If you're parsing data from http ://website.com/login.php to http://www.website.com/fb-callback.php this would be a cross-domain problem and the error you are receiving would be because of that....
http ://website.com and http ://www.website.com are the same but the script identifies them as different..... hope that gives insight to the problem.

Facebook Login using HybridAuth showing error You cannot access this page directly

I am trying to write a plugin for my website to connect with facebook using the HybridAuth
classes.
I just tried following code
function authenticatewith( $provider ) {
ini_set('display_errors','on');
//includes
$config = dirname(__FILE__) . '/hybridauth-2.1.2/hybridauth/config.php';
require_once("hybridauth-2.1.2/hybridauth/Hybrid/Auth.php");
$provider_name = $provider;
//$config = $this->getconfig($id);
try {
// initialize Hybrid_Auth with a given file
$hybridauth = new Hybrid_Auth($config);
// try to authenticate with the selected provider
$adapter = $hybridauth->authenticate($provider_name);
// then grab the user profile
$user_profile = $adapter->getUserProfile();
}
catch( Exception $e ) {
echo "Error: please try again!";
echo "Original error message: " . $e->getMessage();
}
echo "User Details: ";
var_dump($user_profile);
}
When I call this function form the plugin class. In the browser it shows the following error:
You cannot access this page directly.
...and the URL in the address bar of the browser is something like this:
http://zyx.com/oinmonm/plugins/sociallogin/hybridauth-2.1.2/hybridauth/?hauth.start=Facebook&hauth.time=1415168326
After searching stackoverflow I found a similar question that describes about similar problem, but I have not been able to figure out how to apply the suggestions there to my code fix the issue:
You cannot access this page directly - HybridAuth Social Login
Most probably the problem is with the different domain names, as my website is running on two different domains.
How can I fix my code to prevent this issue?
More Details
I have a facebook link on www.bca.com(example) then when you click it goes to a controller.php file that will access the plugin that I am writing . Usually if I save a folder in the website like the plugin folder that is not accessible by www.bca.com instead its accessible by some other domain name .
What I am trying to say is that the session is starting in bca.com but the Hybridauth classes are saved in some other domain . And I think this is the reason the error is coming.
I tried to debug and found out the error is popping from following lines in Endpoint.php file
// Check if Hybrid_Auth session already exist
if (! $storage->config("CONFIG")) {
header("HTTP/1.0 404 Not Found");
die("You cannot access this page directly.");
}
I have been trying to fix this from last 3 days . But I am stuck at this point plz some one help me out.
Thanks in advance
Try after adding #session_start(); statement at the top of your files.
I had the same issue. It relates to our custom session handler which is set by session_set_save_handler().
Hybrid Auth uses standard PHP sessions, so after redirecting and opening a new session, Hybrid Auth starts using standard PHP file sessions instead of your custom session handler. This result in the loss of config data from our session and getting this error message.
I resolved this issue by adding our own custom session handler at the top of hybridauth/index.php (located in the same dir as config.php and live.php).
This forces Hybrid Auth to use your custom session handler.
For anyone with the same problem have a question: The file that calls the API is in the same directory it?
Me only worked when I put my file in the same folder as the config.php file. Try it there and tell me if it works!

How to remove extra information from a URL

I noticed that when I put a link in my LinkedIn updates LinkedIn feels the need to add '#!' to the end of the URL . That seems to be a problem when I try to show off a calendar my company has installed.
SO I figure I would just link to a PHP file and redirect from there to the calendar. But even after specifying an absolute URL in the code, the '#!' is still appended to the end of the end of the URL.
The code I was using for that redirect:
<?php
$url = "http://calendar.example.com";
header( 'location:'.$url ) ;
?>
Still sends me to http://calendar.exmpale.com/#!
How do I convince the code to remove that '#!' that is causing problems? Also, why does LinkedIn do this?
Hashes are only client side you can not use mod_rewrite to remove it as mentioned above. I would use javascript.
window.location.href.substr(0, window.location.href.indexOf('#'))

How to deep link to a Facebook App (NOT Page Tab)

I need to link to a specific page in my Facebook app. The app is not in a page tab, and cannot be in one due to the project constrictions.
This is the url format:
https://apps.facebook.com/myappname
I would need to pass a parameter at the end (like /next.html or ?page=next) so that I can link to the specific page directly from outside the app (from an email).
How would I set this up? My project uses PHP and jQuery. I would love to be able to do this strictly in Javascript if possible.
I have found tons of info on how to deep link a page tab or a mobile app, but not to a regular application. I have found messages stating it's possible, but nothing about how to actually do it anywhere online or on Facebook.
Thanks for your help.
EDIT:
Okay, I got it working in PHP. For anyone else with this issue, this is what I did.
Add a "?" at the very end of the 'Site URL' in your FB app, then create a redirect file similar to this as your app landing page (just use absolute paths instead of relative ones like I did below):
<?php
$query = $_SERVER['QUERY_STRING'];
$params = explode("/", $query);
if (in_array("gallery", $params)) {
header("Location: /gallery.html");
exit;
}
else {
header("Location: /index.html");
exit;
}
?>
This answer is what helped me figure this out:
$_GET on facebook iframe app
I may be missing something here, but why don't you just link to http://apps.facebook.com/yourapp/something.php - this should automatically load your canvas URL, with something.php appended to the path
Obviously this won't work if your canvas URL points to a specific file and not a directory, but plenty of apps do this with success
When you are using the ? all you are doing is issuing a $_GET request, so all of the info you require will exist in the $_GET array.
Rather than query the $_SERVER array, query the $_GET array.
So if you had:
http://myurl.com?info=foobar
You can simply access that info using:
$info = $_GET['info'];
It is good practice to check for the existence first though:
if (isset($_GET['info']))
{
$info =$_GET['info'];
}
else
{
$info="default";
}
Incidently if you use the & character you can have multiple parameters:
http://myurl.com?info=foo&moreinfo=bar
You get a special parameter called app_data that you can use however you want. I've used it in the past to encode a full querystring of my internal app. for example, &app_data=My/Custom/Page
More found in this SO question: Retrieve Parameter From Page Tab URL

Zend Framework: From a folder (not /)

i notice that when i run a zend framework app from a server, there are alot of side effects. main issue is where i use urls like
/auth/login
i need to use
$this->baseUrl('/auth/login');
thats simple to fix. but when i use
$request->getRequestUri()
for use in redirects. eg after login, i want to redirect the user back to the prev page, it goes to the wrong place. eg. my app root is "http://localhost/app1", $request->getRequestUri() will give /app1. when i try to redirect back, it will goto http://localhost/app1/app1. btw, i am using Zend Server + IIS7 and my app is configured to run from the url stated above. maybe i shld be going to "/" instead. how can i resolve this?
update
this is in my Zend_Form class
// (Zend_Form) Login.php init()
$req = Zend_Controller_Front::getInstance()->getRequest();
$returnUrl = $req->getParam('returnUrl', $req->getRequestUri());
$this->addElement('hidden', 'returnUrl', array(
'value' => $returnUrl
));
// AuthController after login
$returnUrl = urldecode($form->getElement('returnUrl')->getValue());
if (!empty($returnUrl)) {
$this->_helper->getHelper('Redirector')->setGotoUrl($returnUrl);
}
Based on you update:
Its the prependBase-Option in the Redirector what you are looking for:
prependBase: boolean flag indicating whether or not to prepend the base URL when a relative URL is provided
So your fix is:
$this->_helper->getHelper('Redirector')->setGotoUrl($returnUrl, array('prependBase' => false));
If you are using Zend_Application you can use this in your application.ini, and wont need to specify anything else.
resources.frontController.baseUrl = "/your/public/path/"
I have solved this problem with help of Apache configs. In file \usr\local\apache\conf\vhosts.conf find a block with your site and change ways and public folder.

Categories