Using Middleware in CakePHP “3.next”
Middleware support will be come in CakePHP 3.3.0, but you can try it now, there is a branch for it named “3.next”! If you want to start with composer create-project, you can run with the following command:
composer create-project --prefer-dist cakephp/app <dir-target> dev-3.next
By specifying “dev-3.next” after directory target, you will pull the 3.next branch of “cakephp/app”. Once it done, you will now have an Application class inside src/ that bootstrap the application and also setup the middleware your application will use:
namespace App; class Application extends BaseApplication { public function bootstrap(){ /** **/} public function middleware($middleware) { $middleware->push(new ErrorHandlerMiddleware()); $middleware->push(new AssetMiddleware()); $middleware->push(new RoutingMiddleware()); return $middleware; } }
Now, let say you want to add your own middleware, named “Authorization” middleware, let’s create it:
namespace App\Middleware; use Cake\Network\Session; use Cake\Core\Configure; use Zend\Diactoros\Response\RedirectResponse; class Authorization { public function __invoke($request, $response, $next) { $session = Session::create(Configure::read('Session')); $checkHasUserSession = $session->check('user'); $path = $request->getUri()->getPath(); if ($path === '/admin' && ! $checkHasUserSession) { return new RedirectResponse('/auth'); } return $next($request, $response); } }
The “Authorization” middleware we just created now needs to be registered via middleware->push:
namespace App; use App\Middleware\Authorization; class Application extends BaseApplication { public function middleware($middleware) { $middleware->push(new ErrorHandlerMiddleware()); $middleware->push(new AssetMiddleware()); $middleware->push(new RoutingMiddleware()); //add the Authorization middleware $middleware->push(new Authorization()); return $middleware; } }
Done 😉
References:
1. http://www.slideshare.net/markstory/future-of-http-in-cakephp
I am getting ‘The page isn’t redirecting properly’ error while redirecting using below code .
public function __invoke($request, $response, $next)
{
$path = $request->getUri()->getPath();
if ($path === ‘/admin/index’) {
return new RedirectResponse($path,200);
}
return $next($request, $response);
}
I am new to cakephp and I would like to create a middleware to authenticate each controller action. Above code is an example.
because your code is redirect to same page with current page, check your code:
that will always got endless redirect.
how can i create unit test for session on middleware?
i’ve tried using common session property, or using Session::write, neither of it can read the session when tested
thx in advance
mock and stub that, you may need try to use kahlan: http://kahlan.readthedocs.io/en/latest/
How can I add csrf in this and how to use in other controller methods
https://book.cakephp.org/3.0/en/controllers/components/csrf.html#using-the-csrfcomponent