使用 composer 从 CakePHP 项目的根目录(包含 **composer.json** 文件的位置)安装插件
php composer.phar require "cakephp/authorization:^3.0"
授权插件的 3.0 版本与 CakePHP 5 兼容。
通过在项目的 src/Application.php
中添加以下语句来加载插件
$this->addPlugin('Authorization');
授权插件作为中间件层集成到您的应用程序中,可以选择使用组件来简化授权检查。首先,让我们应用中间件。在 **src/Application.php** 中,将以下内容添加到类导入中
use Authorization\AuthorizationService;
use Authorization\AuthorizationServiceInterface;
use Authorization\AuthorizationServiceProviderInterface;
use Authorization\Middleware\AuthorizationMiddleware;
use Authorization\Policy\OrmResolver;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
将 AuthorizationServiceProviderInterface
添加到您应用程序中实现的接口上
class Application extends BaseApplication implements AuthorizationServiceProviderInterface
然后使您的应用程序的 middleware()
方法如下所示
public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue
{
// Middleware provided by CakePHP
$middlewareQueue->add(new ErrorHandlerMiddleware(Configure::read('Error')))
->add(new AssetMiddleware())
->add(new RoutingMiddleware($this))
->add(new BodyParserMiddleware())
// If you are using Authentication it should be *before* Authorization.
->add(new AuthenticationMiddleware($this))
// Add the AuthorizationMiddleware *after* routing, body parser
// and authentication middleware.
->add(new AuthorizationMiddleware($this));
return $middlewareQueue();
}
AuthorizationMiddleware
的放置位置很重要,必须在身份验证中间件之后添加。这确保了请求包含一个可以用于授权检查的 identity
。
AuthorizationMiddleware
将在开始处理请求时调用应用程序上的挂钩方法。此挂钩方法允许您的应用程序定义它要使用的 AuthorizationService
。将以下方法添加到您的 **src/Application.php** 中
public function getAuthorizationService(ServerRequestInterface $request): AuthorizationServiceInterface
{
$resolver = new OrmResolver();
return new AuthorizationService($resolver);
}
这配置了基本的 策略解析器,它将 ORM 实体与其策略类匹配。
接下来,让我们将 AuthorizationComponent
添加到 AppController
。在 **src/Controller/AppController.php** 中,将以下内容添加到 initialize()
方法中
$this->loadComponent('Authorization.Authorization');
通过加载 AuthorizationComponent,我们将能够更轻松地在每个动作的基础上检查授权。例如,我们可以执行以下操作
public function edit($id = null)
{
$article = $this->Article->get($id);
$this->Authorization->authorize($article, 'update');
// Rest of action
}
通过调用 authorize
,我们可以使用我们的 策略 来强制执行应用程序的访问控制规则。您可以使用 存储在请求中的身份 在任何地方检查权限。