How to check CSRF in every FORMS ??

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?

Hey bro. Drop code where you render hidden field in view.



9.9k

Hi, here is my code:

{{ form('users/login', 'id': 'signin-form_id') }}
<div class="form-group">
    {{ form.render('name') }}
    <span class="fa fa-user signin-form-icon"></span>
</div>
<div class="form-group">
    {{ form.render('password') }}
    <span class="fa fa-lock signin-form-icon"></span>
</div>
<div class="form-group">
    <label class="checkbox-inline">
        {{ form.render('remember') }}
        <span class="lbl">Remember Me</span>
    </label>
</div>
<div class="form-actions">
    {{ form.render(form.getCsrfName()) }}
    <input type="submit" value="登 录" class="signin-btn bg-warning"> 
</div>
{{ endForm() }}


9.9k

any advice?

>Hey bro. Drop code where you render hidden field in view.



9.9k

I think this way could run correctly, but it's not....I can't find any bugs

>Hey bro. Drop code where you render hidden field in view.