0

我终于将我的应用程序升级到 cakephp 3.2,因为我解决了 3.1+ 的另一个问题

长话短说,我正在使用Xety CookieAuth让我的用户在他们回到我的网站时自动登录,并且在 Cake 3.0 中一切都完美无缺。

在 3.2 中,我遇到“找不到页面”错误,我可以在我的日志文件中看到:

2016-01-31 12:49:42 Error: [Cake\Network\Exception\InvalidCsrfTokenException] Missing CSRF token cookie

我究竟做错了什么?我试图查看是否有其他东西需要升级,检查了文档,但一切似乎都是正确的......

编辑:我注意到如果我从我的 AppController 中删除它,一切似乎都在工作。但后来我失去了自动登录功能......

if (!$this->Auth->user() && $this->Cookie->read('CookieAuth')) {
    $this->request->data = $this->Cookie->read('CookieAuth');
    $user = $this->Auth->identify();
    $this->loadModel('Users');

    if ($user) {
        $this->Auth->setUser($user);

        /* Check which browser version is in use */
        $userData = $this->Users->find('all')->where(['id' => $user['id']])->first();
        $userData->browser = $this->Browser->getData();
        $this->Users->save($userData);

        /* Check if the user has the contract_accepted flag set to true */
        if ($userData->contract_accepted != true) {
            $this->request->session()->write("checkContract", true);
        }

    } else {
        $this->Cookie->delete('CookieAuth');
    }
}

编辑

经过几次尝试并感谢 ndm 为我指明了正确的方向,我发现我最初的问题(我已经通过一个丑陋的 hack 解决了)是 CookieAuth 没有正确应用来自我的 cookie 的数据。我在 CookieAuthenticate.php 中添加了几个调试,这就是我发现的:

debug($this->_config['fields']);

/vendor/xety/cake3-cookieauth/src/Auth/CookieAuthenticate.php (line 46)
[
    'username' => 'username',
    'password' => 'password'
]

debug($cookies);

/vendor/xety/cake3-cookieauth/src/Auth/CookieAuthenticate.php (line 47)
[
    'email' => 'info@mydomain.com',
    'password' => 'mypassword'
]

那么,我怎样才能告诉插件我没有使用用户名,而是使用电子邮件呢?

$this->loadComponent('Auth', [
    'authenticate' => [
        'Form' => [
            'fields' => ['username' => 'email']
        ],
        'Xety/Cake3CookieAuth.Cookie'
    ],
    'loginRedirect' => '/',
    'logoutRedirect' => '/',
]);
4

2 回答 2

1

我发现了问题所在。加载 Cake3CookieAuth 组件时,您需要告诉它应该使用哪些字段进行身份验证。所以这是错误的,并产生错误:

$this->loadComponent('Auth', [
    'authenticate' => [
        'Form' => [
            'fields' => ['username' => 'email']
        ],
        'Xety/Cake3CookieAuth.Cookie'
    ],
    ...
]);

这是更正后的代码:

$this->loadComponent('Auth', [
    'authenticate' => [
        'Form' => [
            'fields' => ['username' => 'email']
        ],
        'Xety/Cake3CookieAuth.Cookie' => [
            'fields' => ['username' => 'email']
        ]
    ],
    ...
]);
于 2016-02-02T08:54:39.500 回答
0

您没有使用插件文档中建议的代码,您不应该读取 cookie 并将其写入请求数据,这将使 cookie 验证器无用,因为它不会再被触发,因为表单验证器将找到请求数据并将其用于身份验证。

由于此更改,现在发生错误:

https://github.com/cakephp/cakephp/pull/7938

它使 CSRF 验证不仅在请求为 、 或 时应用POST,而且PUT在有可用请求数据时应用(无论它来自何处)。PATCHDELETE

于 2016-02-01T10:43:30.840 回答