Skip to content

Commit

Permalink
Merge pull request #57 from dejanceltra/basic-auth-support-non-ascii-…
Browse files Browse the repository at this point in the history
…characters

Fix basic auth to support non-ascii characters
  • Loading branch information
sirn-se authored May 22, 2024
2 parents 50ad647 + fe8d6ae commit 1859826
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 5 deletions.
14 changes: 12 additions & 2 deletions src/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -501,8 +501,18 @@ protected function performHandshake(Uri $uri): Response
->withHeader('Sec-WebSocket-Version', '13');

// Handle basic authentication.
if ($userinfo = $uri->getUserInfo()) {
$request = $request->withHeader('Authorization', 'Basic ' . base64_encode($userinfo));
$components = $uri->getComponents();
if (array_key_exists('user', $components)) {
$user = urldecode($components['user']);

if (array_key_exists('pass', $components)) {
$pass = $components['pass'];
$credentials = urldecode($user) . ':' . urldecode($pass);
} else {
$credentials = urldecode($user);
}

$request = $request->withHeader('Authorization', 'Basic ' . base64_encode($credentials));
}

// Add and override with headers.
Expand Down
28 changes: 25 additions & 3 deletions tests/suites/client/ConfigTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

namespace WebSocket\Test\Client;

use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use Phrity\Net\Mock\StreamFactory;
use Phrity\Net\Mock\Stack\{
Expand Down Expand Up @@ -131,17 +132,38 @@ public function testUriInstanceWssDefaultPort(): void
unset($client);
}

public function testUriStringAuthorization(): void
public static function uriStringAuthorizationDataProvider(): array
{
$encoded = urlencode('7{v^pF8;uPK.6VWu');

return [
[
'usename:password',
'dXNlbmFtZTpwYXNzd29yZA==',
],
[
'usename',
'dXNlbmFtZQ==',
],
[
"{$encoded}:{$encoded}",
'N3t2XnBGODt1UEsuNlZXdTo3e3ZecEY4O3VQSy42Vld1',
],
];
}

#[DataProvider('uriStringAuthorizationDataProvider')]
public function testUriStringAuthorization(string $uriAuth, string $expectedCredentials): void
{
$this->expectStreamFactory();
$client = new Client('wss://usename:password@localhost:8000/my/mock/path');
$client = new Client("wss://{$uriAuth}@localhost:8000/my/mock/path");
$client->setStreamFactory(new StreamFactory());

$this->expectWsClientConnect(scheme: 'ssl');
$this->expectWsClientPerformHandshake(
'localhost:8000',
'/my/mock/path',
"Authorization: Basic dXNlbmFtZTpwYXNzd29yZA==\r\n"
"Authorization: Basic {$expectedCredentials}\r\n"
);
$client->connect();

Expand Down

0 comments on commit 1859826

Please sign in to comment.