【问题标题】:CakePHP 3.5 Writing & Encrypting CookieCakePHP 3.5 编写和加密 Cookie
【发布时间】:2018-11-13 09:27:27
【问题描述】:

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

我有一个写 cookie 的代码。但是,似乎我缺少一些加密它的步骤。有人可以阐明缺少的步骤在哪里吗?目前,网络浏览器正在获取 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 数据集也将被加密。但对我来说它不会自动加密?

【问题讨论】:

    标签: cakephp cookies cakephp-3.0 cakephp-3.5


    【解决方案1】:

    您可能想让自己更熟悉中间件的工作方式,您不应该在控制器中使用它们,它们应该被“包裹”在您的应用程序中,并与发送到应用程序,以及应用程序发回的响应。

    您在应用程序的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;
        }
    }
    

    另见

    【讨论】:

      猜你喜欢
      • 2018-11-11
      • 2013-11-30
      • 2018-09-21
      • 2011-02-17
      • 1970-01-01
      • 2015-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多