CakePHP 3.5写作&加密Cookie

时间:2018-06-04 05:30:19

标签: cakephp cookies cakephp-3.0 cakephp-3.5

背景:我刚刚升级到CakePHP 3.5.17。

我有一个写cookie的代码。但是,似乎我错过了加密它的几个步骤。有人可以在缺少步骤的地方掏出一些灯吗?目前,Web浏览器正在获取cookie的值,但它未加密。注意我还在app.php上设置了cookieKey

我还在下面提供的链接中包含了这些步骤

https://book.cakephp.org/3.0/en/development/application.html#adding-http-stack

//In src/Controller/UsersController.php

use Cake\I18n\Time; 
use Cake\Http\Cookie\Cookie;
use Cake\Http\Cookie\CookieCollection;    
use Cake\Core\Configure;  
use App\Application;
use Cake\Error\Middleware\ErrorHandlerMiddleware;
use Cake\Http\MiddlewareQueue;
use Cake\Routing\Middleware\AssetMiddleware;
use Cake\Routing\Middleware\RoutingMiddleware;
use Cake\Http\Middleware\EncryptedCookieMiddleware;

     public function writecookie() {

        $cookie = new Cookie(
            'goodday', // name
            'YES', // value
            (Time::now())->modify('+1 year'), // expiration time, if applicable
            '/', // path, if applicable
            '', // domain, if applicable
            false, // secure only?
            true // http only ?
        );

        $middlewareQueue = new MiddlewareQueue();           

        $cookiesEncrypted = new EncryptedCookieMiddleware(
            ['goodday'],
            Configure::read('Security.cookieKey')
        );

        $cookiesEncrypted = $middlewareQueue->add($cookiesEncrypted);

        $this->response = $this->response->withCookie($cookie); //value is still YES in the web browser cookie storage

    }

进一步调试后,我注意到在EncryptedCookieMiddleware类中。它声明请求数据中的Cookie将被解密,而响应头中的cookie将自动加密。如果响应是Cake \ Http \ Response,则使用withCookie()和`cookie()``设置的cookie数据也将被加密。但对我来说它不会自动加密?

1 个答案:

答案 0 :(得分:2)

你可能想让自己更熟悉中间件如何工作,你不应该在你的控制器中使用它们,它们应该被包裹起来""您的应用程序并与发送到应用程序的请求以及应用程序发回的响应进行交互。

您可以在应用Application::middleware()方法,Server.buildMiddleware事件或连接路线时注册它们。

// src/Application.php

// ...
use Cake\Http\Middleware\EncryptedCookieMiddleware;

class Application extends BaseApplication
{
    public function middleware($middlewareQueue)
    {
        // ...
        $middlewareQueue->add(new EncryptedCookieMiddleware(/* ... */));
        return $middlewareQueue;
    }
}

另见