gomes81/guzzlehttp-cookie-auth-subscriber

0.3.0 2022-05-26 02:18 UTC

This package is auto-updated.

Last update: 2024-09-26 07:45:36 UTC


README

使用Cookies签署HTTP请求。请求通过包含用户名和密码(以及/或您希望包含的任何其他字段)的登录表单进行签署。然后,凭证将通过指定的HTTP方法(通常是POST)发送到提供的URL,并将返回的Cookies保存供以后使用。

本版本仅适用于Guzzle 6.0及以上版本!

安装

可以使用Composer安装此项目。请将以下内容添加到您的composer.json中

{
    "require": {
        "gomes81/guzzlehttp-cookie-auth-subscriber": "0.1.*"
    }
}

使用订阅者

以下是一个示例,展示如何发送经过身份验证的请求

use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use Gomes81\GuzzleHttp\Subscriber\CookieAuth;

$stack = HandlerStack::create();

$middleware = new CookieAuth(
    '/login_simple_url_or_path',
    [
        'username'    => 'my_username',
        'password'    => 'my_password',
        'other_field' => 'my_field_value'
    ],
    'POST',// GET, POST or JSON (will JSON encode fields array and send it inside the POST request body)
    'you can also pass a cookie string to use in here');
$stack->push($middleware);

$client = new Client([
    'base_uri' => 'http://simple_url.com',
    'handler'  => $stack
]);

// Set the "auth" request option to "cookie" to sign the request using a cookie
// Before calling the given url the subscriber will check if there's a valid cookie
// to be injected in the current request, if a valid cookie could not be found an
// additional request is made to obtain it
$res = $client->get('statuses/home_timeline.json', ['auth' => 'cookie']);

您可以通过在提供给new Client的数组中扩展auth => cookie来设置auth请求选项,以便客户端发送的所有请求都使用cookie。

use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use Gomes81\GuzzleHttp\Subscriber\CookieAuth;

$stack = HandlerStack::create();

$middleware = new CookieAuth(
    '/login_simple_url_or_path', [
        'username'    => 'my_username',
        'password'    => 'my_password',
        'other_field' => 'my_field_value'],
    'POST',// GET, POST or JSON (will JSON encode fields array and send it inside the POST request body)
    'you can also pass a cookie string to use in here');
$stack->push($middleware);

$client = new Client([
    'base_uri' => 'http://simple_url.com',
    'handler'  => $stack,
    'auth'     => 'cookie'
]);

// Now you don't need to add the auth parameter
$res = $client->get('statuses/home_timeline.json');

您还可以通过在第四个参数中传递FileCookieJar对象实例来将Cookies保存到文件中。

use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Cookie\FileCookieJar;
use Gomes81\GuzzleHttp\Subscriber\CookieAuth;

$stack = HandlerStack::create();

$middleware = new CookieAuth(
    '/login_simple_url_or_path', [
        'username'    => 'my_username',
        'password'    => 'my_password',
        'other_field' => 'my_field_value'],
    'POST',// GET, POST or JSON (will JSON encode fields array and send it inside the POST request body)
    new FileCookieJar('./cookies_folder/cookie_file_name', true));
$stack->push($middleware);