【发布时间】:2020-12-07 15:05:49
【问题描述】:
我正在使用 CakePHP 4。 根据文档,我设置了“记住我”cookie,当我通过登录时,我在浏览器中看到 CookieAuth 控制器的用户名和密码值正确。 关键是当我注销时,我仍然在浏览器中看到 cookie(它将在几天后过期),但我希望登录表单中带有预编译值的用户名和密码输入文本。 这是正确的行为吗? 我试图填充这些字段,但在与 cookie 读取/写入相关的许多不同错误中发生 传递给 Cake\Http\Response::withCookie() 的参数 1 必须实现接口 Cake\Http\Cookie\CookieInterface, string given
这是我的代码:
在 app_local.php 中:
‘Security’ => [
‘salt’ => env(‘SECURITY_SALT’, ‘string’, //here my random string
],
-在Application.php中
$cookies = new EncryptedCookieMiddleware(
[‘CookieAuth’],
Configure::read(‘Security.cookieKey’)
);
在getAuthenticationService(ServerRequestInterface $request)内部,在Session之后和Form之前:
$authenticationService->loadAuthenticator(‘Authentication.Cookie’, [
‘rememberMeField’ => ‘remember_me’,
‘fields’ => [
‘username’ => ‘email’,
‘password’ => ‘password’,
],
‘loginUrl’ => ‘/’,
‘cookie’=>[
‘name’=>‘CookieAuth’,
‘expire’=> new DateTime(‘Thu, 31 Dec 20 15:00:00 +0000’)
]
]);
在UsersController中,登录功能
public function login()
{
$this->Authorization->skipAuthorization();
$cookie = [‘email’=>’’, ‘password’=>’’, ‘remember_me’=>0];
if ($this->request->getCookie('CookieAuth')) {
$cookie = $this->request->getCookie('CookieAuth');
debug('cookie');
}
// if remember_me
if($this->request->getData('remember_me') == 1) {
$this->response = $this->response->withCookie(new Cookie('CookieAuth'), $this->request->getData());
}
else {
//$this->Cookie->delete('CookieAuth');
}
$this->set($cookie);
// other code
}
-模板\用户\login.php:
<?= $this->Form->control('email', ['required' => true]) ?>
<?= $this->Form->control('password', ['required' => true]) ?>
<?= $this->Form->control('remember_me', ['type' => 'checkbox']);?>
<?= $this->Form->submit(__('Login')); ?>
任何帮助将不胜感激,谢谢。
【问题讨论】:
-
Remember Me cookie 用于在会话过期后返回网站时自动创建新的登录会话。如果您注销,它应该会消失。记住您的用户名并在登录表单中预先填充它不是什么东西。
标签: cookies cakephp-4.x