Skip to content

Commit

Permalink
Add test for AccessTokenHeaderRegex and adjust regex
Browse files Browse the repository at this point in the history
A new test was added to AccessTokenAuthenticatorTest to ensure that the regular expression in HeaderAccessTokenExtractor works correctly. The regular expression was tweaked to support a wider range of tokens, especially those ending with an equals sign.
  • Loading branch information
Spomky committed Apr 18, 2024
1 parent a99669c commit 01643fd
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
2 changes: 1 addition & 1 deletion AccessToken/HeaderAccessTokenExtractor.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public function __construct(
private readonly string $tokenType = 'Bearer'
) {
$this->regex = sprintf(
'/^%s([a-zA-Z0-9\-_\+~\/\.]+)$/',
'/^%s([a-zA-Z0-9\-_\+~\/\.]+=*)$/',
'' === $this->tokenType ? '' : preg_quote($this->tokenType).'\s+'
);
}
Expand Down
28 changes: 28 additions & 0 deletions Tests/Authenticator/AccessTokenAuthenticatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
use Symfony\Component\Security\Core\User\InMemoryUserProvider;
use Symfony\Component\Security\Http\AccessToken\AccessTokenExtractorInterface;
use Symfony\Component\Security\Http\AccessToken\AccessTokenHandlerInterface;
use Symfony\Component\Security\Http\AccessToken\HeaderAccessTokenExtractor;
use Symfony\Component\Security\Http\Authenticator\AccessTokenAuthenticator;
use Symfony\Component\Security\Http\Authenticator\FallbackUserLoader;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
Expand Down Expand Up @@ -159,4 +160,31 @@ public function testAuthenticateWithFallbackUserLoader()

$this->assertEquals('test', $passport->getUser()->getUserIdentifier());
}

/**
* @dataProvider provideAccessTokenHeaderRegex
*/
public function testAccessTokenHeaderRegex(string $input, ?string $expectedToken)
{
// Given
$extractor = new HeaderAccessTokenExtractor();
$request = Request::create('/test', 'GET', [], [], [], ['HTTP_AUTHORIZATION' => $input]);

// When
$token = $extractor->extractAccessToken($request);

// Then
$this->assertEquals($expectedToken, $token);
}

public function provideAccessTokenHeaderRegex(): array
{
return [
['Bearer token', 'token'],
['Bearer mF_9.B5f-4.1JqM', 'mF_9.B5f-4.1JqM'],
['Bearer d3JvbmdfcmVnZXhwX2V4bWFwbGU=', 'd3JvbmdfcmVnZXhwX2V4bWFwbGU='],
['Bearer Not Valid', null],
['Bearer (NotOK123)', null],
];
}
}

0 comments on commit 01643fd

Please sign in to comment.