Skip to content

[Security] Fix loading user from UserBadge #51104

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
Aug 25, 2023
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
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,18 @@ public function testSelfContainedTokens()
$this->assertSame(['message' => 'Welcome @dunglas!'], json_decode($response->getContent(), true));
}

public function testCustomUserLoader()
{
$client = $this->createClient(['test_case' => 'AccessToken', 'root_config' => 'config_custom_user_loader.yml']);
$client->catchExceptions(false);
$client->request('GET', '/foo', [], [], ['HTTP_AUTHORIZATION' => 'Bearer SELF_CONTAINED_ACCESS_TOKEN']);
$response = $client->getResponse();

$this->assertInstanceOf(Response::class, $response);
$this->assertSame(200, $response->getStatusCode());
$this->assertSame(['message' => 'Welcome @dunglas!'], json_decode($response->getContent(), true));
}

/**
* @requires extension openssl
*/
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
imports:
- { resource: ./../config/framework.yml }

framework:
http_method_override: false
serializer: ~

security:
password_hashers:
Symfony\Component\Security\Core\User\InMemoryUser: plaintext

providers:
in_memory:
memory:
users:
dunglas: { password: foo, roles: [ROLE_MISSING] }

firewalls:
main:
pattern: ^/
stateless: true
access_token:
token_handler: access_token.access_token_handler
token_extractors: 'header'
realm: 'My API'

access_control:
- { path: ^/foo, roles: ROLE_USER }

services:
access_token.access_token_handler:
class: Symfony\Bundle\SecurityBundle\Tests\Functional\Bundle\AccessTokenBundle\Security\Handler\AccessTokenHandler
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
use Symfony\Component\Security\Http\AccessToken\AccessTokenHandlerInterface;
use Symfony\Component\Security\Http\AccessToken\Oidc\Exception\InvalidSignatureException;
use Symfony\Component\Security\Http\AccessToken\Oidc\Exception\MissingClaimException;
use Symfony\Component\Security\Http\Authenticator\FallbackUserLoader;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;

/**
Expand Down Expand Up @@ -93,7 +94,7 @@ public function getUserBadgeFrom(string $accessToken): UserBadge
}

// UserLoader argument can be overridden by a UserProvider on AccessTokenAuthenticator::authenticate
return new UserBadge($claims[$this->claim], fn () => $this->createUser($claims), $claims);
return new UserBadge($claims[$this->claim], new FallbackUserLoader(fn () => $this->createUser($claims)), $claims);
} catch (\Exception $e) {
$this->logger?->error('An error occurred while decoding and validating the token.', [
'error' => $e->getMessage(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Http\AccessToken\AccessTokenHandlerInterface;
use Symfony\Component\Security\Http\AccessToken\Oidc\Exception\MissingClaimException;
use Symfony\Component\Security\Http\Authenticator\FallbackUserLoader;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Contracts\HttpClient\HttpClientInterface;

Expand Down Expand Up @@ -48,7 +49,7 @@ public function getUserBadgeFrom(string $accessToken): UserBadge
}

// UserLoader argument can be overridden by a UserProvider on AccessTokenAuthenticator::authenticate
return new UserBadge($claims[$this->claim], fn () => $this->createUser($claims), $claims);
return new UserBadge($claims[$this->claim], new FallbackUserLoader(fn () => $this->createUser($claims)), $claims);
} catch (\Exception $e) {
$this->logger?->error('An error occurred on OIDC server.', [
'error' => $e->getMessage(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ public function authenticate(Request $request): Passport
}

$userBadge = $this->accessTokenHandler->getUserBadgeFrom($accessToken);
if ($this->userProvider) {
if ($this->userProvider && (null === $userBadge->getUserLoader() || $userBadge->getUserLoader() instanceof FallbackUserLoader)) {
$userBadge->setUserLoader($this->userProvider->loadUserByIdentifier(...));
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

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

namespace Symfony\Component\Security\Http\Authenticator;

use Symfony\Component\Security\Core\User\UserInterface;

/**
* This wrapper serves as a marker interface to indicate badge user loaders that should not be overridden by the
* default user provider.
*
* @internal
*/
final class FallbackUserLoader
{
public function __construct(private $inner)
{
}

public function __invoke(mixed ...$args): ?UserInterface
{
return ($this->inner)(...$args);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\User\OidcUser;
use Symfony\Component\Security\Http\AccessToken\Oidc\OidcTokenHandler;
use Symfony\Component\Security\Http\Authenticator\FallbackUserLoader;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;

/**
Expand Down Expand Up @@ -61,7 +62,7 @@ public function testGetsUserIdentifierFromSignedToken(string $claim, string $exp
))->getUserBadgeFrom($token);
$actualUser = $userBadge->getUserLoader()();

$this->assertEquals(new UserBadge($expected, fn () => $expectedUser, $claims), $userBadge);
$this->assertEquals(new UserBadge($expected, new FallbackUserLoader(fn () => $expectedUser), $claims), $userBadge);
$this->assertInstanceOf(OidcUser::class, $actualUser);
$this->assertEquals($expectedUser, $actualUser);
$this->assertEquals($claims, $userBadge->getAttributes());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\User\OidcUser;
use Symfony\Component\Security\Http\AccessToken\Oidc\OidcUserInfoTokenHandler;
use Symfony\Component\Security\Http\Authenticator\FallbackUserLoader;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;
Expand Down Expand Up @@ -47,7 +48,7 @@ public function testGetsUserIdentifierFromOidcServerResponse(string $claim, stri
$userBadge = (new OidcUserInfoTokenHandler($clientMock, null, $claim))->getUserBadgeFrom($accessToken);
$actualUser = $userBadge->getUserLoader()();

$this->assertEquals(new UserBadge($expected, fn () => $expectedUser, $claims), $userBadge);
$this->assertEquals(new UserBadge($expected, new FallbackUserLoader(fn () => $expectedUser), $claims), $userBadge);
$this->assertInstanceOf(OidcUser::class, $actualUser);
$this->assertEquals($expectedUser, $actualUser);
$this->assertEquals($claims, $userBadge->getAttributes());
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
<?php

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

namespace Authenticator;

use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\User\InMemoryUser;
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\Authenticator\AccessTokenAuthenticator;
use Symfony\Component\Security\Http\Authenticator\FallbackUserLoader;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;

class AccessTokenAuthenticatorTest extends TestCase
{
private AccessTokenHandlerInterface $accessTokenHandler;
private AccessTokenExtractorInterface $accessTokenExtractor;
private InMemoryUserProvider $userProvider;

protected function setUp(): void
{
$this->accessTokenHandler = $this->createMock(AccessTokenHandlerInterface::class);
$this->accessTokenExtractor = $this->createMock(AccessTokenExtractorInterface::class);
$this->userProvider = new InMemoryUserProvider(['test' => ['password' => 's$cr$t']]);
}

public function testAuthenticateWithoutAccessToken()
{
$this->expectException(BadCredentialsException::class);
$this->expectExceptionMessage('Invalid credentials.');

$request = Request::create('/test');

$this->accessTokenExtractor
->expects($this->once())
->method('extractAccessToken')
->with($request)
->willReturn(null);

$authenticator = new AccessTokenAuthenticator(
$this->accessTokenHandler,
$this->accessTokenExtractor,
);

$authenticator->authenticate($request);
}

public function testAuthenticateWithoutProvider()
{
$request = Request::create('/test');

$this->accessTokenExtractor
->expects($this->once())
->method('extractAccessToken')
->with($request)
->willReturn('test');
$this->accessTokenHandler
->expects($this->once())
->method('getUserBadgeFrom')
->with('test')
->willReturn(new UserBadge('john', fn () => new InMemoryUser('john', null)));

$authenticator = new AccessTokenAuthenticator(
$this->accessTokenHandler,
$this->accessTokenExtractor,
$this->userProvider,
);

$passport = $authenticator->authenticate($request);

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

public function testAuthenticateWithoutUserLoader()
{
$request = Request::create('/test');

$this->accessTokenExtractor
->expects($this->once())
->method('extractAccessToken')
->with($request)
->willReturn('test');
$this->accessTokenHandler
->expects($this->once())
->method('getUserBadgeFrom')
->with('test')
->willReturn(new UserBadge('test'));

$authenticator = new AccessTokenAuthenticator(
$this->accessTokenHandler,
$this->accessTokenExtractor,
$this->userProvider,
);

$passport = $authenticator->authenticate($request);

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

public function testAuthenticateWithUserLoader()
{
$request = Request::create('/test');

$this->accessTokenExtractor
->expects($this->once())
->method('extractAccessToken')
->with($request)
->willReturn('test');
$this->accessTokenHandler
->expects($this->once())
->method('getUserBadgeFrom')
->with('test')
->willReturn(new UserBadge('john', fn () => new InMemoryUser('john', null)));

$authenticator = new AccessTokenAuthenticator(
$this->accessTokenHandler,
$this->accessTokenExtractor,
$this->userProvider,
);

$passport = $authenticator->authenticate($request);

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

public function testAuthenticateWithFallbackUserLoader()
{
$request = Request::create('/test');

$this->accessTokenExtractor
->expects($this->once())
->method('extractAccessToken')
->with($request)
->willReturn('test');
$this->accessTokenHandler
->expects($this->once())
->method('getUserBadgeFrom')
->with('test')
->willReturn(new UserBadge('test', new FallbackUserLoader(fn () => new InMemoryUser('john', null))));

$authenticator = new AccessTokenAuthenticator(
$this->accessTokenHandler,
$this->accessTokenExtractor,
$this->userProvider,
);

$passport = $authenticator->authenticate($request);

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