I want to check CSRF in every Forms, so I code a base form:
class FormBase extends Form
{
protected $_csrf;
public function initialize()
{
$csrf = new Hidden($this->getCsrfName());
$csrf->addValidator(new Identical([
'value' => $this->security->getSessionToken(),
'message' => 'Forgery!'
]));
$csrf->clear();
$this->add($csrf);
}
public function messages($name)
{
if ($this->hasMessagesFor($name)) {
foreach ($this->getMessagesFor($name) as $message) {
$this->flash->error($message);
}
}
}
// Generates CSRF token key
public function getCsrfName()
{
if (empty($this->_csrf)) {
$this->_csrf = $this->security->getTokenKey();
}
return $this->_csrf;
}
}
And the login form extends from the base:
class LoginForm extends FormBase
{
public function initialize()
{
parent::initialize();
// Username
$username = new Text('name', array(
'class' => 'form-control input-lg',
'placeholder' => 'Username'
));
$this->add($username);
// Password
$password = new Password('password', array(
'class' => 'form-control input-lg',
'placeholder' => 'Password'
));
$this->add($password);
}
}
And in the webpage of login form, I can see the csrf token, but when I submit the form, it always says "Forgery!
"
Why? and how to correct?