dasprid / helios
PSR-7 认证中间件
Requires
- php: ^7.1
- cultuurnet/clock: ^1.0
- dasprid/pikkuleipa: ^2.0
- dasprid/treereader: ^1.1
- psr/http-message: ^1.0
- psr/http-server-middleware: ^1.0
Requires (Dev)
- phpunit/phpunit: ^5.5
- psr/container: ^1.0
- squizlabs/php_codesniffer: ^2.7
- zendframework/zend-diactoros: ^1.3
Suggests
- psr/container: For using the supplied factories
README
Helios 是一个拥抱 PSR-7 的认证中间件。它的目的是使身份完全依赖于请求,同时通过使用 JSON Web Tokens 避免使用服务器端会话。
安装
通过 composer 安装
$ composer require dasprid/helios
入门(针对 Expressive)
JWT Cookies
此库使用 Pikkuleipa,这是一个利用 JSON Web Tokens 的 Cookie 管理器。为了开始使用 Helios,您需要先 配置 Pikkuleipa。
导入工厂配置
在您的自动加载配置目录中创建一个名为 helios.global.php
或类似的文件
<?php return (new DASPRiD\Helios\ConfigProvider())->__invoke();
这将引入几个工厂,您可以通过以下方式检索以下对象
DASPRiD\Helios\IdentityCookieManager
通过DASPRiD\Helios\IdentityCookieManager
DASPRiD\Helios\IdentityMiddleware
通过DASPRiD\Helios\IdentityMiddleware
创建身份查找
您需要实现一个查找,根据存储在令牌中的主题检索用户身份。在您的依赖项容器中注册该查找
<?php use DASPRiD\Helios\Identity\IdentityLookupInterface; use DASPRiD\Helios\Identity\LookupResult; class MyIdentityLookup implements IdentityLookupInterface { public function lookup($subject) : LookupResult { // Pseudo-code here if ($this->repository->has($subject)) { return LookupResult::fromIdentity($this->repository->get($subject)); } return LookupResult::invalid(); } }
然后通过更新配置文件将您的实现连接到 Helios
<?php return [ 'helios' => [ // ... 'identity_lookup_id' => MyIdentityLookup::class, ], ];
配置 Helios
为了使 Helios 运行,它需要一些配置变量。复制文件 doc/example-config.php
并根据需要调整值。
注册身份中间件
Helios 随带了一个 IdentityMiddleware
,应在发送中间件之前将其注册到您的中间件管道中。确切位置取决于您的需求。
编写您的登录中间件
Helios 本身不提供任何实际的用户登录或登出的逻辑。因此,一个简单的登录中间件可能看起来像这样
<?php class MySignIn { /** * @var \DASPRiD\Helios\IdentityCookieManager */ private $identityCookieManager; public function __invoke() { // Verify the user if ($userIsValid) { $response = new Zend\Diactoros\Response\RedirectResponse('/go/somewhere'); return $this->identityCookieManager->injectCookie( $response, $user->getId(), ! $rememberMeSelected ); } // Do some error response here } }
编写您的登出中间件
与登录中间件类似,您的登出中间件可以使用 IdentityCookieManager
使 cookie 无效
<?php class MySignOut { /** * @var \DASPRiD\Helios\IdentityCookieManager */ private $identityCookieManager; public function __invoke() { $response = new Zend\Diactoros\Response\RedirectResponse('/go/somewhere'); return $this->identityCookieManager->expireCookie($response); } }
在中间件中检索用户身份
每次通过 IdentityMiddleware
检索用户时,它都会作为属性注入到请求中。因此,当您需要在中间件中获取用户时,可以轻松地获取它
<?php use DASPRiD\Helios\IdentityMiddleware; use Psr\Http\Message\ServerRequestInterface; class SomeOtherMiddleware { public function __invoke(ServerRequestInterface $request) { $user = $request->getAttribute(IdentityMiddleware::IDENTITY_ATTRIBUTE); } }
有时可能需要在您的视图中始终可用身份,例如在布局中显示用户名。处理这种情况的正确方法是使用特定的模板渲染器,它除了常用的视图参数外,还接受请求对象,并在渲染前将用户注入到视图变量中。但是,尽量避免将整个请求对象注入到视图参数中。