在将 授权中间件 应用于您的应用程序并将 identity
添加到请求后,您可以开始检查授权。中间件将在每个请求中将 identity
包装在一个 IdentityDecorator
中,该装饰器添加了与授权相关的方法。
您可以将 identity
传递到您的模型、服务或模板中,以便您在应用程序的任何地方轻松地检查授权。有关如何自定义或替换默认装饰器,请参见 身份装饰器 部分。
can
方法使您能够检查单个资源的授权。通常,这将是一个 ORM 实体或应用程序域对象。您的 策略 提供逻辑来做出授权决定
// Get the identity from the request
$user = $this->request->getAttribute('identity');
// Check authorization on $article
if ($user->can('delete', $article)) {
// Do delete operation
}
如果您的策略返回 策略结果对象,请确保检查其状态,因为 canResult()
返回结果实例
// Assuming our policy returns a result.
$result = $user->canResult('delete', $article);
if ($result->getStatus()) {
// Do deletion
}
当您需要将授权检查应用于像分页查询这样的对象集合时,您通常希望只获取当前用户有权访问的记录。此插件将此概念实现为“范围”。范围策略允许您“限制”查询或结果集并返回更新的列表或查询对象
// Get the identity from the request
$user = $this->request->getAttribute('identity');
// Apply permission conditions to a query so only
// the records the current user has access to are returned.
$query = $user->applyScope('index', $query);
授权组件 可用于控制器操作中,以简化授权检查,这些检查在失败时会引发异常。