los/api-auth

API认证中间件

资助包维护!
Lansoweb

1.3.1 2023-09-19 18:52 UTC

README

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

此库提供PHP中间件用于API认证。

安装

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: 从授权头提取身份和凭证
  • Aggregate: 您可以添加任意多的策略,它将返回第一个成功的策略
  • 策略接口以实现自己的策略

认证器

包含

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

输出

包含

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