首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PEAR QuickForm2 CSRF保护

PEAR QuickForm2 CSRF保护
EN

Stack Overflow用户
提问于 2015-05-12 10:01:35
回答 1查看 231关注 0票数 1

我正在寻找一种方法,以确保CSRF-Protection在我的Quickform2

我找到了这个链接,但这是给QuickForm1的。

有什么想法可以让我适应QF2吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-05-12 10:01:35

经过一番周旋之后,我想出了这个解决方案。

也许这对其他人也有帮助:

代码语言:javascript
复制
<?php

/**
 * @uses HTML_QuickForm
 * @desc Add automatic CSRF mitigation to all forms by incorporating a token that must be matched in the session and forcing the use of POST method
 * Based on: http://www.zapoyok.info/2010/07/17/csrf-et-quickform-de-pear/
 */
require_once "QuickForm2.php";

class HTML_QuickForm2s extends HTML_QuickForm2
{
    /**
     * @property string $_sessionTokenKey The name of the session variable containing the token
     */
    private $_sessionTokenKey;

    /**
     * @method __construct
     * @desc Override the method to always use post and pass it on to the parent constructor. Create a session key for the token based on the form name.
     * @param $id
     * @param string $method
     * @param mixed $attributes
     * @param boolean $trackSubmit
     */
    public function __construct($id, $method = 'post', $attributes = null, $trackSubmit = true)
    {
        $this->_sessionTokenKey = "QuickForm2s_" . md5($id);

        parent::__construct($id, $method, $attributes, $trackSubmit);

        //A token hasn't been created so do so
        if (!isset($_SESSION[$this->_sessionTokenKey])) {
            $_SESSION[$this->_sessionTokenKey] = md5(uniqid(rand(), true) . session_id()); //requires the session id to be known in order to add extra difficulty to compromising
        }

        //Hide the token at the end of the form
        $this->addElement("hidden", "qfS_csrf");

        $qfsCsrf= $this->getElementsByName('qfS_csrf');
        $qfsCsrf[0]->setValue($_SESSION[$this->_sessionTokenKey]);
    }

    /**
     * @method validate
     * @desc Check if the passed token matches the session before allowing validation
     * @return boolean
     */
    public function validate()
    {
        $submitValues = $this->getValue();

        //The token was not passed or does not match
        if (!isset($submitValues['qfS_csrf']) || $submitValues['qfS_csrf'] != $_SESSION[$this->_sessionTokenKey]) {
            $this->setError("Anti-CSRF token does not match");
        }

        return parent::validate();
    }

}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30187551

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档