bdunogier / guzzle-site-authenticator
一个guzzle插件,必要时会向请求中添加认证数据。使用凭证和cookie,对网站进行登录请求。
Requires
- guzzlehttp/guzzle: ^5.3.1
- psr/log: ^1.0.0
- symfony/config: ^4.4|^5.4|^6.0
- symfony/dependency-injection: ^4.4|^5.4|^6.0
- symfony/expression-language: ^4.4|^5.4|^6.0
- symfony/http-kernel: ^4.4|^5.4|^6.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.4.0
- monolog/monolog: ^2.3
- nyholm/symfony-bundle-test: ^2.0
- symfony/phpunit-bridge: ^6.0
This package is auto-updated.
Last update: 2024-09-21 16:42:55 UTC
README
此包是guzzle 5.x的插件。它提供了一个可以发布登录信息的订阅者来认证请求。
它以Symfony包和通用PHP库的形式出现。
安装
使用composer
使用composer将包添加到您的需求中:composer require bdunogier/guzzle-site-authenticator
。
如果您使用的是Symfony全栈,请将BD\GuzzleSiteAuthenticatorBundle\BDGuzzleSiteAuthenticatorBundle
添加到您的内核类中。
使用
guzzle订阅者Guzzle\AuthenticatorSubscriber
必须附加到Guzzle客户端。它由包作为@bd_guzzle_site_authenticator.authenticator_subscriber
提供
$client = new GuzzleHttp\Client(['defaults' => ['cookies' => new FileCookieJar('/tmp/cookiejar.json')]]); $client->getEmitter()->attach( $container->get('bd_guzzle_site_authenticator.authenticator_subscriber') );
cookie处理
传递给guzzle客户端的默认CookieJar
很重要:它将用于读取/写入Guzzle接收到的cookie,并且对于认证正常工作是必需的。
使用Guzzle发送请求。如果请求的主机有一个需要配置的SiteConfig(见下文),并且还没有cookie,插件将尝试登录到该网站。请求后,如果响应包含未登录的文本(通过xpath匹配),它将再次尝试登录并重试请求。
站点配置
通过SiteConfig
对象登录配置的网站
$siteConfig = new BD\GuzzleSiteAuthenticator\SiteConfig\SiteConfig([ 'host' => 'example.com', 'loginUri' => 'http://example.com/login', 'usernameField' => 'username', 'passwordField' => 'password', 'extraFields' => ['action' => 'login'], 'notLoggedInXpath' => "//div[@class='not-logged-in']", 'username' => "johndoe", 'password' => "unknown", ]);
SiteConfig
对象由SiteConfigBuilder
返回。库附带一个默认的ArraySiteConfigBuilder
,它接受一个按主机索引的网站配置属性数组。使用包,其内容可以使用bd_guzzle_site_authenticator.site_config
容器变量进行配置
# config.yml parameters: bd_guzzle_site_authenticator.site_config: example.com: host: "example.com" loginUri: "http://example.com/login" usernameField: "username" passwordField: "password" extraFields: {action: login} notLoggedInXpath: "//div[@class='not-logged-in']" username: "johndoe" password: "unknown" otherexample.com: host: ...
实现
由wallabag使用,这是一个阅读后应用程序,用于从需要登录的网站获取内容。
它实现了一个自定义的SiteConfigBuilder
,基于j0k3r/graby提供的站点配置。