innmind / http-authentication

4.0.0 2023-11-01 08:32 UTC

This package is auto-updated.

Last update: 2024-08-30 01:32:11 UTC


README

Build Status codecov Type Coverage

一个简单的请求身份验证工具。

该库依赖于2个原则

  • 一个身份,它是一个表示尝试登录的实体(用户、应用程序等)的对象
  • 一个验证器,它将尝试从请求中提取信息(登录/密码、令牌等),然后将其解析为身份

这里的目的是要有一个非常简单的东西,不需要你的领域逻辑从这个库中实现或扩展任何东西。这是通过拥有Identity接口来实现的,你的领域实体应该已经使用一个接口来表示其身份,因此你只需要在这个库中实现该接口的类。

安装

composer require innmind/http-authentication

用法

use Innmind\HttpAuthentication\{
    Identity,
    Any,
    ViaBasicAuthorization,
    ViaBasicAuthorization\Resolver as BasicResolver,
    ViaForm,
    ViaForm\Resolver as FormResolver,
};

$auth = bootstrap();
$viaBasicAuthorization = new ViaBasicAuthorization(
    new class implements BasicResolver {
        public function __invoke(string $user, string $password): Identity
        {
            // this info comes from the Authorization header

            // your logic here to authenticate the user
        }
    }
);
$viaForm = new ViaForm(
    new class implements FormResolver {
        public function __invoke(Form $form): Identity
        {
            // your logic here to authenticate the user by inspecting
            // the form, you have access to the whole form data so the
            // library doesn't force you to have specific fields
        }
    }
);
$authenticate = new Any(
    $viaBasicAuthorization,
    $viaForm
);

$identity = $authenticate(/* an instance of Innmind\Http\Message\ServerRequest */)->match(
    static fn($identity) => $identity,
    static fn() => throw new \RuntimeException('Unknown identity'),
);

三个解析器都是可选的,因此你可以选择使用哪一个。因为所有验证器都实现了相同的接口,你可以轻松地装饰验证器来添加自己的逻辑,例如在会话中持久化身份(默认为无状态)。