webignition / guzzle-http-authentication-middleware
为Guzzle6提供的Http认证中间件
0.5
2019-03-25 16:47 UTC
Requires
- php: >=7.2.0
- psr/http-message: ~1.0
Requires (Dev)
README
概述
中间件 用于 Guzzle 6,在客户端发送的所有请求上设置 基本HTTP认证。
任何有效请求都会添加一个认证头。一个有效请求是指请求的主机与预先指定的域名相匹配。
如果您的环境符合以下所有或部分情况,则该中间件很有用:
- 您需要为特定域的客户发送的所有请求设置HTTP认证
- 您不希望为每个请求特别添加一个授权头,尤其是当应用程序中有很多地方需要发送请求时
- 您无法预先确定请求可能发送到哪些域名,并且您不希望通过在每个请求上设置授权头来泄露凭据
也许,这正好适合您。
使用示例
use GuzzleHttp\Client; use GuzzleHttp\HandlerStack; use webignition\Guzzle\Middleware\HttpAuthentication\AuthorizationType; use webignition\Guzzle\Middleware\HttpAuthentication\AuthorizationHeader; use webignition\Guzzle\Middleware\HttpAuthentication\CredentialsFactory; use webignition\Guzzle\Middleware\HttpAuthentication\HttpAuthenticationMiddleware; // Creating a client that uses the middleware $httpAuthenticationMiddleware = new HttpAuthenticationMiddleware(); $handlerStack = HandlerStack::create(); $handlerStack->push($httpAuthenticationMiddleware, 'http-auth'); $client = new Client([ 'handler' => $handlerStack, ]); // Setting credentials on the middleware $basicCredentials = CredentialsFactory::createBasicCredentials('username', 'password'); $httpAuthenticationMiddleware->setType(AuthorizationType::BASIC); $httpAuthenticationMiddleware->setCredentials($credentials); $httpAuthenticationMiddleware->setHost('example.com'); // All requests to example.com (or *.example.com) will now have // a correct Authorization header set for basic HTTP authentication
应用层考虑
假设您正在构建一个使用控制器、服务等的现代PHP应用程序。
将您的 HttpAuthenticationMiddleware
实例定义为一个 服务。使用依赖注入将此服务注入到需要设置HTTP认证凭据的应用程序部分的任何部分。根据需要调用 HttpAuthenticationMiddleware::setHttpAuthenticationCredentials()
,传递包含相关值的 HttpAuthenticationCredentials
实例。