mimmi20/mezzio-generic-authorization

为 Mezzio 和 PSR-7 应用提供授权中间件。

3.0.7 2024-09-16 04:39 UTC

README

Latest Stable Version Latest Unstable Version License

代码状态

codecov Test Coverage Average time to resolve an issue Percentage of issues still open Mutation testing badge Maintainability

安装

您可以使用 Composer 安装 mezzio-generic-authorization 库。

composer require mimmi20/mezzio-generic-authorization

简介

此组件为 MezzioPSR-7 应用提供中间件,根据 ACLRBAC 系统授权特定路由。

mezzio-authorization 不同,此库默认不要求 ServerRequestInterface。这使得可以与 mezzio-navigation 结合使用。

如果使用提供的中间件,则使用 路由名称 作为资源。

授权系统首先需要进行认证:为了验证一个身份是否有权访问某些东西(即是否被授权),我们首先需要 身份,它是在认证过程中提供的。

认证通过 mezzio-authentication 包提供。该库提供了一个 AuthenticationMiddleware 类,它使用 HTTP 请求验证凭据,并通过 PSR-7 请求属性 存储身份。

mezzio-authentication 生成的身份存储为请求属性 Mezzio\Authentication\UserInterfaceUserInterface 实现。该接口如下所示

namespace Mezzio\Authentication;

interface UserInterface
{
    /**
     * Get the unique user identity (id, username, email address or ...)
     */
    public function getIdentity() : string;

    /**
     * Get all user roles
     *
     * @return Iterable
     */
    public function getRoles() : iterable;

    /**
     * Get a detail $name if present, $default otherwise
     */
    public function getDetail(string $name, $default = null);

    /**
     * Get all the details, if any
     */
    public function getDetails() : array;
}

mezzio-generic-authorization 消费此身份属性。它检查用户角色(从 UserInterface 对象获取)是否被授权(允许)执行当前 HTTP 请求。

使用 AuthorizationInterfaceisGranted() 方法执行授权。

public function isGranted(?string $role = null, ?string $resource = null, ?string $privilege = null, ?\Psr\Http\Message\ServerRequestInterface\ServerRequestInterface $request = null): bool;

有两个适配器可用

如果您想了解更多关于使用中间件进行 PHP 认证的信息,我们建议阅读博客文章"使用中间件授权用户"

授权适配器

您可以通过服务容器配置配置要使用的授权适配器。具体来说,您可以将服务名称 Mimmi20\Mezzio\GenericAuthorization\AuthorizationInterface 映射到工厂,或者将其别名为适当的服务。

例如,使用 Mezzio 容器配置,您可以选择以下任一方式选择 mezzio-authorization-acl 适配器

  • 使用别名

    use Mimmi20\Mezzio\GenericAuthorization\AuthorizationInterface;
    use Mimmi20\Mezzio\GenericAuthorization\Acl\LaminasAcl;
    
    return [
        'dependencies' => [
            // Using an alias:
            'aliases' => [
                AuthorizationInterface::class => LaminasAcl::class,
            ],
        ],
    ];
  • 映射到工厂

    use Mimmi20\Mezzio\GenericAuthorization\AuthorizationInterface;
    use Mimmi20\Mezzio\GenericAuthorization\Acl\LaminasAclFactory;
    
    return [
        'dependencies' => [
            // Using a factory:
            'factories' => [
                AuthorizationInterface::class => LaminasAclFactory::class,
            ],
        ],
    ];

我们提供了两种不同的适配器。

每个适配器都可以通过Composer安装。

composer require mimmi20/mezzio-generic-authorization-rbac
# or
composer require mimmi20/mezzio-generic-authorization-acl

许可证

本软件包使用MIT许可证授权。

请参阅LICENSE.md