zooxsmart/los-api-auth

API 认证中间件

资助包维护!
Lansoweb

1.0.2 2023-12-19 12:50 UTC

This package is auto-updated.

Last update: 2024-09-19 14:18:27 UTC


README

codecov GitHub license GitHub Workflow Status GitHub release (latest by date) Packagist PHP Version Support

此库提供了一个用于 API 认证的 PHP 中间件。

安装

composer require los/api-auth

用法

使用 PSR-11 容器,使用提供的工厂并定义每个需求的工厂

return [
    \Los\ApiAuth\ApiAuth::class => \Los\ApiAuth\ApiAuthFactory::class,
    \Los\ApiAuth\Strategy\Strategy::class => \Los\ApiAuth\Strategy\XApiKeyHeader::class,
    \Los\ApiAuth\Authenticator\Authenticator::class => \Los\ApiAuth\Authenticator\ArrayAuthenticatorFactory::class,
    \Los\ApiAuth\Output\Output::class => \Los\ApiAuth\Output\ProblemDetailsOutputFactory::class,
];

然后将中间件添加到您的管道中

$app->pipe(\Los\ApiAuth\ApiAuth::class);

如果成功,中间件将使用找到的标识注册一个新的请求属性 Los\ApiAuth\Authenticator\Authenticator,这样您就可以知道哪个标识被授权在请求中。

如果使用 laminas,您可以创建一个 config/autoload/api-auth.global.php

<?php

declare(strict_types=1);

use Los\ApiAuth\ApiAuth;
use Los\ApiAuth\ApiAuthFactory;
use Los\ApiAuth\Authenticator\ArrayAuthenticatorFactory;
use Los\ApiAuth\Authenticator\Authenticator;
use Los\ApiAuth\Output\Output;
use Los\ApiAuth\Output\ProblemDetailsOutputFactory;
use Los\ApiAuth\Strategy\BasicAuthorizationHeader;
use Los\ApiAuth\Strategy\Strategy;

return [
    'dependencies' => [
        'invokables' => [
            Strategy::class => BasicAuthorizationHeader::class,
        ],
        'factories'  => [
            ApiAuth::class       => ApiAuthFactory::class,
            Authenticator::class => ArrayAuthenticatorFactory::class,
            Output::class        => ProblemDetailsOutputFactory::class,
        ],
    ],
    'api-auth'     => [
        'ignorePaths' => ['/health'], 
        'identities'  => ['707cd425-0a60-4d36-b2e8-c9fd7fc0f194' => '208bfbc5-e705-46b1-aec0-2b0e1b4156ad'],
    ],
];

策略

包含

  • XApiKeyHeader: 从 X-Api-Key 头中提取标识
  • CustomHeader: 从自定义头中提取标识
  • AuthorizationHeader: 从 Authorization 头中提取标识和凭证
  • Aggregate: 您可以添加任意数量的策略,并且它将返回第一个成功的策略
  • 策略接口以实现您自己的策略

认证器

包含

  • ArrayAuthenticator: 将标识/凭证与简单数组进行验证。默认是 ['api-auth']['identities']
  • 认证器接口以实现您自己的,例如数据库

输出

包含

  • ProblemDetailOutput: 将使用 mezzio/problem-details 包生成 JSON 响应输出,您需要在 composer.json 中引入它
  • ExceptionOutput: 它将只是抛出异常,您可以在其他中间件中处理它
  • 输出接口以实现您自己的,例如 HTML、XML