缺少Csrf令牌cookie

时间:2019-05-07 17:13:22

标签: cakephp cookies csrf middleware cakephp-3.7

我是CakePHP(v3.7)的新手。我有一个应用程序,其中出现“缺少Csrf令牌Cookie”错误。

在Application.php中,我有:

$options = [];        // I'm fine with the default options.
$csrf = new CsrfProtectionMiddleware($options);
$middlewareQueue->add($csrf);

表单页面包含一个隐藏的表单元素,其中包含 _csrfToken 。 为什么在POST上找不到它,我感到困惑?

进一步研究,我发现在 CsrfProtectionMiddleware.php 中,以下 _validateToken()函数的行为如下:

$ cookies null (未设置cookie。) 因此, $ cookie

$ post 实际上包含页面上隐藏参数中 _csrfToken 参数的内容。但是该函数从不看它。由于 $ cookie 为空, if(!$ cookie)语句导致引发 InvalidCsrfTokenException

    protected function _validateToken(ServerRequest $request)
    {
        $cookies = $request->getCookieParams();
        $cookie = Hash::get($cookies, $this->_config['cookieName']);
        $post = Hash::get($request->getParsedBody(), $this->_config['field']);
        $header = $request->getHeaderLine('X-CSRF-Token');

        if (!$cookie) {
            throw new InvalidCsrfTokenException(__d('cake', 'Missing CSRF token cookie'));
        }

        if (!Security::constantEquals($post, $cookie) && !Security::constantEquals($header, $cookie)) {
            throw new InvalidCsrfTokenException(__d('cake', 'CSRF token mismatch.'));
        }
    }
}

很明显,除了隐藏参数之外,中间件还期望使用 actual cookie。这个Cookie在哪里设置(或应该设置在哪里?)

更新:

我在浏览器端进行了检查。已设置cookie,但浏览器未在POST请求中返回它。

这是CakePHP对原始GET请求的响应,以填充页面:

Connection: Keep-Alive
Content-Length: 3013
Content-Type: text/html; charset=UTF-8
Date: Wed, 08 May 2019 23:07:31 GMT
Keep-Alive: timeout=5, max=100
Server: Apache/2.4.33 (Unix) PHP/7.1.1
Set-Cookie: csrfToken=b553dd2e06e57f6d514ee41a120e1c60084adafddfbaa6f72db1f7f590fcf50143876ac817d29d6f1cf9a786031d6235ba21e265b9d3b2a0ee4535854f048b66; path=/webroot/
X-Powered-By: PHP/7.1.1

注意csrfToken cookie。 ...这是浏览器将表单数据发送回的POST

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
Cache-Control: no-cache
Connection: keep-alive
Content-Length: 184
Content-Type: application/x-www-form-urlencoded
DNT: 1
Host: *************
Origin: ****************
Pragma: no-cache
Referer: ***************
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36

查询字符串参数

redirect: /Users/login

表格数据

_method: POST
_csrfToken:  b553dd2e06e57f6d514ee41a120e1c60084adafddfbaa6f72db1f7f590fcf50143876ac817d29d6f1cf9a786031d6235ba21e265b9d3b2a0ee4535854f048b66
username: xxxxxxxxxx
password: xxxxxxxxxx

请注意,它将发送回隐藏的表单参数 _csrfToken ,而不是cookie。

感谢您的帮助...

1 个答案:

答案 0 :(得分:0)

已解决。原来这是Apache中DOCUMENT_ROOT目录设置的问题。它被设置为webroot的父目录,而不是webroot本身。当我更改它时,一切正常。