cphalcon icon indicating copy to clipboard operation
cphalcon copied to clipboard

[BUG]: Can't generate CSRF token

Open feloot opened this issue 6 years ago • 3 comments

Describe the bug I am unable to generate the CSRF token. It always returns null.

To Reproduce Code to reproduce the behavior:

<?php
session_start();

use	Phalcon\Mvc\Application,
	Phalcon\Di\FactoryDefault;
	
$di = new FactoryDefault();

$di->setShared('security', function() use ($di) {
	$security = new \Phalcon\Security();
	$security->setDI($di);
	$security->setWorkFactor(12);
	return $security;
});

$di->setShared('session', function() {
	$session = new \Phalcon\Session\Manager();
	$files = new \Phalcon\Session\Adapter\Stream([
		'savePath' => sys_get_temp_dir()
	]);
	$session
		->setAdapter($files)
		->start();
	return $session;
});

$application = new Application($di);

echo "<pre>";
var_dump($di->get('session')->exists()); // true
var_dump($di->get('session')->getId()); // eqkv927hvbr26rev9t4kpco71k
var_dump($di->get('security')->checkToken()); // false
var_dump($di->get('security')->getSessionToken()); // NULL

Expected behavior Both the session and security services being loaded, the CSRF token should be generated automatically according to the docs (https://docs.phalcon.io/4.0/en/security). Hence checkToken() should return true.

Details

  • Phalcon version: 4.0.0
  • PHP Version: 7.4.1
  • Operating System: Debian 10 on Docker
  • Installation type: Compiling from source
  • Server: Nginx 1.17.6

Additional context I've also tried with PHP 7.2 but I've got the same issue. The default temp dir is /tmp, it is writeable and I can see the session in there (eqkv927hvbr26rev9t4kpco71k). I've got no errors in my php/nginx logs.

Thanks !

feloot avatar Jan 09 '20 23:01 feloot

CheckToken expect that a post value is present and getToken is called. So normally you use this when handeling the post of a form. Our tests looks something like this.

$security = $di->get('security');
$tokenKey = $security->getTokenKey();
$token    = $security->getToken();

$_POST = [
        $tokenKey => $token,
];
$security->checkToken(); //returns true

See our docs as well. https://docs.phalcon.io/4.0/en/security#csrf-protection

ruudboon avatar Jan 10 '20 06:01 ruudboon

Hi @ruudboon,

You're absolutely right about this, my mistake this was driving me insane yesterday but for some reason it works this morning as $security->getToken() now returns a key. I'm guessing there was some kind of cache somewhere I'm not aware about.

Thank you again and sorry for the trouble.

feloot avatar Jan 10 '20 08:01 feloot

@Feloot No prob. Enjoy v4

ruudboon avatar Jan 10 '20 09:01 ruudboon