Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[HttpClient] Allow to pass user/pw as an array #30556

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 14, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion src/Symfony/Component/HttpClient/HttpClientTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,17 @@ private static function prepareRequest(?string $method, ?string $url, array $opt
throw new InvalidArgumentException(sprintf('Option "on_progress" must be callable, %s given.', \is_object($onProgress) ? \get_class($onProgress) : \gettype($onProgress)));
}

if (\is_array($options['auth_basic'] ?? null)) {
$count = \count($options['auth_basic']);
if ($count <= 0 || $count > 2) {
throw new InvalidArgumentException(sprintf('Option "auth_basic" must contain 1 or 2 elements, %s given.', $count));
}

$options['auth_basic'] = implode(':', $options['auth_basic']);
}

if (!\is_string($options['auth_basic'] ?? '')) {
throw new InvalidArgumentException(sprintf('Option "auth_basic" must be string, %s given.', \gettype($options['auth_basic'])));
throw new InvalidArgumentException(sprintf('Option "auth_basic" must be string or an array, %s given.', \gettype($options['auth_basic'])));
}

if (!\is_string($options['auth_bearer'] ?? '')) {
Expand Down
7 changes: 5 additions & 2 deletions src/Symfony/Component/HttpClient/HttpOptions.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,12 @@ public function toArray(): array
/**
* @return $this
*/
public function setAuthBasic(string $userinfo)
public function setAuthBasic(string $user, string $password = '')
{
$this->options['auth'] = $userinfo;
$this->options['auth_basic'] = $user;
if ('' !== $password) {
$this->options['auth_basic'] .= ':'.$password;
}

return $this;
}
Expand Down
19 changes: 18 additions & 1 deletion src/Symfony/Component/HttpClient/Tests/HttpClientTraitTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -185,8 +185,25 @@ public function testInvalidAuthBearerOption()
* @expectedException \Symfony\Component\HttpClient\Exception\InvalidArgumentException
* @expectedExceptionMessage Define either the "auth_basic" or the "auth_bearer" option, setting both is not supported.
*/
public function testSetBasicAndBearerOption()
public function testSetAuthBasicAndBearerOptions()
{
self::prepareRequest('POST', 'http://example.com', ['auth_bearer' => 'foo', 'auth_basic' => 'foo:bar'], HttpClientInterface::OPTIONS_DEFAULTS);
}

public function providePrepareAuthBasic()
{
yield ['foo:bar', 'Zm9vOmJhcg=='];
yield [['foo', 'bar'], 'Zm9vOmJhcg=='];
yield ['foo', 'Zm9v'];
yield [['foo'], 'Zm9v'];
}

/**
* @dataProvider providePrepareAuthBasic
*/
public function testPrepareAuthBasic($arg, $result)
{
[, $options] = $this->prepareRequest('POST', 'http://example.com', ['auth_basic' => $arg], HttpClientInterface::OPTIONS_DEFAULTS);
$this->assertSame('Basic '.$result, $options['headers']['authorization'][0]);
}
}
37 changes: 37 additions & 0 deletions src/Symfony/Component/HttpClient/Tests/HttpOptionsTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\HttpClient\Tests;

use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpClient\HttpOptions;

/**
* @author Kévin Dunglas <[email protected]>
*/
class HttpOptionsTest extends TestCase
{
public function provideSetAuth()
{
yield ['user:password', 'user', 'password'];
yield ['user:password', 'user:password'];
yield ['user', 'user'];
yield ['user:0', 'user', '0'];
}

/**
* @dataProvider provideSetAuth
*/
public function testSetAuth(string $expected, string $user, string $password = '')
{
$this->assertSame($expected, (new HttpOptions())->setAuthBasic($user, $password)->toArray()['auth_basic']);
}
}
14 changes: 8 additions & 6 deletions src/Symfony/Contracts/HttpClient/HttpClientInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,9 @@
interface HttpClientInterface
{
public const OPTIONS_DEFAULTS = [
'auth_basic' => null, // string - a username:password enabling HTTP Basic authentication (RFC 7617)
'auth_basic' => null, // array|string - an array containing the username as first value, and optionally the
// password as the second one; or string like username:password - enabling HTTP Basic
// authentication (RFC 7617)
'auth_bearer' => null, // string - a token enabling HTTP Bearer authorization (RFC 6750)
'query' => [], // string[] - associative array of query string values to merge with the request's URL
'headers' => [], // iterable|string[]|string[][] - headers names provided as keys or as part of values
Expand All @@ -37,16 +39,16 @@ interface HttpClientInterface
// the JSON-encoded value and set the "content-type" headers to a JSON-compatible
// value it is they are not defined - typically "application/json"
'user_data' => null, // mixed - any extra data to attach to the request (scalar, callable, object...) that
// MUST be available via $response->getInfo('data') - not used internally
// MUST be available via $response->getInfo('data') - not used internally
'max_redirects' => 20, // int - the maximum number of redirects to follow; a value lower or equal to 0 means
// redirects should not be followed; "Authorization" and "Cookie" headers MUST
// NOT follow except for the initial host name
// redirects should not be followed; "Authorization" and "Cookie" headers MUST
// NOT follow except for the initial host name
'http_version' => null, // string - defaults to the best supported version, typically 1.1 or 2.0
'base_uri' => null, // string - the URI to resolve relative URLs, following rules in RFC 3986, section 2
'buffer' => true, // bool - whether the content of the response should be buffered or not
'on_progress' => null, // callable(int $dlNow, int $dlSize, array $info) - throwing any exceptions MUST abort
// the request; it MUST be called on DNS resolution, on arrival of headers and on
// completion; it SHOULD be called on upload/download of data and at least 1/s
// the request; it MUST be called on DNS resolution, on arrival of headers and on
// completion; it SHOULD be called on upload/download of data and at least 1/s
'resolve' => [], // string[] - a map of host to IP address that SHOULD replace DNS resolution
'proxy' => null, // string - by default, the proxy-related env vars handled by curl SHOULD be honored
'no_proxy' => null, // string - a comma separated list of hosts that do not require a proxy to be reached
Expand Down