0

Background: I have just upgraded to CakePHP 3.5.17.

I had a code that write cookie. However, it seems that I am missing a few steps to encrypt it. Can somebody shed some lights where are the missing steps? At the moment, the web browser is getting the value of the cookie but it is not encrypted. Note I have also set the cookieKey on my app.php

I've also included this steps in the link provided below

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

    }

After further debugging, I noticed that in class EncryptedCookieMiddleware. It is stating that Cookies in request data will be decrypted, while cookies in response headers will be encrypted automatically. If the response is a Cake\Http\Response, the cookie data set with withCookie() and `cookie()`` will also be encrypted. But for me it doesn't automatically encrypt?

EssEss
  • 73
  • 10

1 Answers1

2

You may want to make yourself more familiar with how middlewares work, you're not supposed to use them in your controller, they're supposed to be "wrapped around" your application and interact with the requests that are sent to the app, and the responses that the app sends back.

You register them in your applications Application::middleware() method, in the Server.buildMiddleware event, or when connecting routes.

// src/Application.php

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

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

See also

ndm
  • 59,784
  • 9
  • 71
  • 110