middlewares / http-authentication
实现基本和摘要HTTP认证的中间件
v2.1.2
2024-01-12 17:44 UTC
Requires
- php: ^7.2 || ^8.0
- middlewares/utils: ^3.0 || ^4.0
- psr/http-server-middleware: ^1.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.0
- laminas/laminas-diactoros: ^2.2 || ^3.0
- oscarotero/php-cs-fixer-config: ^1.0
- phpstan/phpstan: ^0.12
- phpunit/phpunit: ^8 || ^9
- squizlabs/php_codesniffer: ^3.0
README
实现RFC 2617 Http Authentication的中间件。包含以下组件
需求
- PHP >= 7.2
- PSR-7 http库
- PSR-15 中间件分发器
安装
此包可通过Composer安装并自动加载,作为middlewares/http-authentication
。
composer require middlewares/http-authentication
BasicAuthentication
基本访问认证是最简单的技术。
您需要提供一个包含所有可用用户用户名和密码的Array
或ArrayAccess
。键是用户名,值是密码。
Dispatcher::run([ new Middlewares\BasicAuthentication([ 'username1' => 'password1', 'username2' => 'password2' ]) ]);
可选地,您可以提供一个Psr\Http\Message\ResponseFactoryInterface
作为第二个参数,该参数将用于创建错误响应(401
)。如果没有定义,将使用Middleware\Utils\Factory自动检测。
$responseFactory = new MyOwnResponseFactory(); $route = new Middlewares\BasicAuthentication($users, $responseFactory);
realm
区域值。默认为"登录"。
attribute
用于保存用户用户名的属性名称。如果没有定义,则不会保存。例如
Dispatcher::run([ (new Middlewares\BasicAuthentication([ 'username1' => 'password1', 'username2' => 'password2' ]))->attribute('username'), function ($request) { $username = $request->getAttribute('username'); return new Response('Hello '.$username); } ]);
verifyHash
此选项使用password_verify
验证密码。如果您不想以纯文本形式提供密码,则很有用。
$users = [ 'username' => password_hash('secret-password', PASSWORD_DEFAULT); ] Dispatcher::run([ (new Middlewares\BasicAuthentication($users)) ->attribute('username') ->verifyHash(), function ($request) { $username = $request->getAttribute('username'); return new Response('Hello '.$username); } ]);
DigestAuthentication
摘要访问认证比基本认证更安全。
构造函数签名与BasicAuthentication
相同
$users = [ 'username1' => 'password1', 'username2' => 'password2' ]; $responseFactory = new MyOwnResponseFactory(); Dispatcher::run([ new Middlewares\DigestAuthentication($users, $responseFactory) ]);
realm
区域值。默认为"登录"。
attribute
用于保存用户用户名的属性名称。如果没有定义,则不会保存。
nonce
配置nonce值。如果没有定义,它将使用uniqid生成
请参阅CHANGELOG以获取有关最近更改的更多信息,并参阅CONTRIBUTING以获取贡献细节。
MIT许可(MIT)。有关更多信息,请参阅LICENSE。