Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
"cakephp/authentication": "^3.0 || ^4.0",
"cakephp/bake": "^3.2",
"cakephp/cakephp": "^5.1",
"cakephp/cakephp-codesniffer": "^5.1",
"cakephp/cakephp-codesniffer": "^5.3",
"phpunit/phpunit": "^10.5.58 || ^11.5.3 || ^12.4 || ^13.0"
},
"suggest": {
Expand Down
20 changes: 20 additions & 0 deletions docs/en/middleware.rst
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,26 @@ option::
'requireAuthorizationCheck' => false
]));

You can also use a Closure to conditionally skip the authorization check based
on the request. This is useful when you need to bypass authorization for specific
routes (e.g., plugin admin panels that manage their own authorization)::

$middlewareQueue->add(new AuthorizationMiddleware($this, [
'requireAuthorizationCheck' => function ($request) {
// Skip authorization check for specific routes
$path = $request->getUri()->getPath();
if (str_contains($path, '/admin/queue')) {
return false;
}

return true;
}
]));

The Closure receives the ``ServerRequestInterface`` and should return a boolean.
Return ``true`` to require authorization check (default behavior), or ``false``
to skip the check for that request.

Handling Unauthorized Requests
------------------------------

Expand Down
10 changes: 8 additions & 2 deletions src/Middleware/AuthorizationMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
use Cake\Core\ContainerApplicationInterface;
use Cake\Core\ContainerInterface;
use Cake\Core\InstanceConfigTrait;
use Closure;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
Expand All @@ -56,7 +57,8 @@ class AuthorizationMiddleware implements MiddlewareInterface
* - `requireAuthorizationCheck` When true the middleware will raise an exception
* if no authorization checks were done. This aids in ensuring that all actions
* check authorization. It is intended as a development aid and not to be relied upon
* in production. Defaults to `true`.
* in production. Defaults to `true`. Can also be a Closure that receives the
* ServerRequestInterface and returns a boolean, allowing route-based control.
*
* @var array<string, mixed>
*/
Expand Down Expand Up @@ -135,7 +137,11 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface
try {
$response = $handler->handle($request);

if ($this->getConfig('requireAuthorizationCheck') && !$service->authorizationChecked()) {
$requireCheck = $this->getConfig('requireAuthorizationCheck');
if ($requireCheck instanceof Closure) {
$requireCheck = $requireCheck($request);
}
if ($requireCheck && !$service->authorizationChecked()) {
throw new AuthorizationRequiredException(['url' => $request->getRequestTarget()]);
}
} catch (Exception $exception) {
Expand Down
64 changes: 64 additions & 0 deletions tests/TestCase/Middleware/AuthorizationMiddlewareTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -316,4 +316,68 @@ public function testMiddlewareInjectsServiceIntoDICViaCustomContainerInstance()

$this->assertEquals($service, $container->get(AuthorizationService::class));
}

public function testRequireAuthorizationCheckCallableReturnsTrue(): void
{
$this->expectException(AuthorizationRequiredException::class);

$service = $this->createMock(AuthorizationServiceInterface::class);
$service->expects($this->once())
->method('authorizationChecked')
->willReturn(false);

$request = (new ServerRequest())->withAttribute('identity', ['id' => 1]);
$handler = new TestRequestHandler();

$middleware = new AuthorizationMiddleware($service, [
'requireAuthorizationCheck' => function (ServerRequestInterface $request): bool {
return true;
},
'identityDecorator' => IdentityDecorator::class,
]);
$middleware->process($request, $handler);
}

public function testRequireAuthorizationCheckCallableReturnsFalse(): void
{
$service = $this->createMock(AuthorizationServiceInterface::class);
$service->expects($this->never())
->method('authorizationChecked');

$request = (new ServerRequest())->withAttribute('identity', ['id' => 1]);
$handler = new TestRequestHandler();

$middleware = new AuthorizationMiddleware($service, [
'requireAuthorizationCheck' => function (ServerRequestInterface $request): bool {
return false;
},
'identityDecorator' => IdentityDecorator::class,
]);
$result = $middleware->process($request, $handler);

$this->assertInstanceOf(ResponseInterface::class, $result);
}

public function testRequireAuthorizationCheckCallableWithRouteBasedLogic(): void
{
$service = $this->createMock(AuthorizationServiceInterface::class);
$service->expects($this->never())
->method('authorizationChecked');

$request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/admin/queue']);
$handler = new TestRequestHandler();

$middleware = new AuthorizationMiddleware($service, [
'requireAuthorizationCheck' => function (ServerRequestInterface $request): bool {
// Skip authorization check for admin/queue routes
$path = $request->getUri()->getPath();

return !str_contains($path, '/admin/queue');
},
'identityDecorator' => IdentityDecorator::class,
]);
$result = $middleware->process($request, $handler);

$this->assertInstanceOf(ResponseInterface::class, $result);
}
}
Loading