Skip to content

[Security] Lazily load the user during the check passport event #37846

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
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 @@ -41,6 +41,7 @@
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Http\Controller\UserValueResolver;
use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface;
use Symfony\Component\Security\Http\Event\CheckPassportEvent;
use Twig\Extension\AbstractExtension;

/**
Expand Down Expand Up @@ -342,6 +343,12 @@ private function createFirewall(ContainerBuilder $container, string $id, array $
throw new InvalidConfigurationException(sprintf('Invalid firewall "%s": user provider "%s" not found.', $id, $firewall['provider']));
}
$defaultProvider = $providerIds[$normalizedName];

if ($this->authenticatorManagerEnabled) {
$container->setDefinition('security.listener.'.$id.'.user_provider', new ChildDefinition('security.listener.user_provider.abstract'))
->addTag('kernel.event_listener', ['event' => CheckPassportEvent::class, 'priority' => 2048, 'method' => 'checkPassport'])
->replaceArgument(0, new Reference($defaultProvider));
}
} elseif (1 === \count($providerIds)) {
$defaultProvider = reset($providerIds);
}
Expand Down Expand Up @@ -632,7 +639,7 @@ private function getUserProvider(ContainerBuilder $container, string $id, array
return $userProvider;
}

if ('remember_me' === $factoryKey || 'anonymous' === $factoryKey) {
if ('remember_me' === $factoryKey || 'anonymous' === $factoryKey || 'custom_authenticators' === $factoryKey) {
return 'security.user_providers';
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,13 @@
use Symfony\Component\Security\Http\Authenticator\RememberMeAuthenticator;
use Symfony\Component\Security\Http\Authenticator\RemoteUserAuthenticator;
use Symfony\Component\Security\Http\Authenticator\X509Authenticator;
use Symfony\Component\Security\Http\Event\CheckPassportEvent;
use Symfony\Component\Security\Http\EventListener\CheckCredentialsListener;
use Symfony\Component\Security\Http\EventListener\PasswordMigratingListener;
use Symfony\Component\Security\Http\EventListener\RememberMeListener;
use Symfony\Component\Security\Http\EventListener\SessionStrategyListener;
use Symfony\Component\Security\Http\EventListener\UserCheckerListener;
use Symfony\Component\Security\Http\EventListener\UserProviderListener;
use Symfony\Component\Security\Http\Firewall\AuthenticatorManagerListener;

return static function (ContainerConfigurator $container) {
Expand Down Expand Up @@ -73,6 +75,18 @@
])
->tag('kernel.event_subscriber')

->set('security.listener.user_provider', UserProviderListener::class)
->args([
service('security.user_providers'),
])
->tag('kernel.event_listener', ['event' => CheckPassportEvent::class, 'priority' => 1024, 'method' => 'checkPassport'])
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this first service used? I may just be missing it

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, the idea is:

  • Always have this service, which chains all configured user providers and runs at 1024
  • If a firewall has provider set, register the same listener for that specific firewall with only the configured firewall at priority 2048

The listener does not configure the user provider if a user loader is already set (e.g. by the authenticator using a closure or by the firewall specific listener).


->set('security.listener.user_provider.abstract', UserProviderListener::class)
->abstract()
->args([
abstract_arg('user provider'),
])

->set('security.listener.password_migrating', PasswordMigratingListener::class)
->args([
service('security.encoder_factory'),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?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\Bundle\SecurityBundle\Tests\Functional;

class AuthenticatorTest extends AbstractWebTestCase
{
/**
* @dataProvider provideEmails
*/
public function testGlobalUserProvider($email)
{
$client = $this->createClient(['test_case' => 'Authenticator', 'root_config' => 'implicit_user_provider.yml']);

$client->request('GET', '/profile', [], [], [
'HTTP_X-USER-EMAIL' => $email,
]);
$this->assertJsonStringEqualsJsonString('{"email":"'.$email.'"}', $client->getResponse()->getContent());
}

/**
* @dataProvider provideEmails
*/
public function testFirewallUserProvider($email, $withinFirewall)
{
$client = $this->createClient(['test_case' => 'Authenticator', 'root_config' => 'firewall_user_provider.yml']);

$client->request('GET', '/profile', [], [], [
'HTTP_X-USER-EMAIL' => $email,
]);

if ($withinFirewall) {
$this->assertJsonStringEqualsJsonString('{"email":"'.$email.'"}', $client->getResponse()->getContent());
} else {
$this->assertJsonStringEqualsJsonString('{"error":"Username could not be found."}', $client->getResponse()->getContent());
}
}

public function provideEmails()
{
yield ['jane@example.org', true];
yield ['john@example.org', false];
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?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\Bundle\SecurityBundle\Tests\Functional\Bundle\AuthenticatorBundle;

use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Http\Authenticator\AbstractAuthenticator;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\PassportInterface;
use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;

class ApiAuthenticator extends AbstractAuthenticator
{
public function supports(Request $request): ?bool
{
return $request->headers->has('X-USER-EMAIL');
}

public function authenticate(Request $request): PassportInterface
{
$email = $request->headers->get('X-USER-EMAIL');
if (false === strpos($email, '@')) {
throw new BadCredentialsException('Email is not a valid email address.');
}

return new SelfValidatingPassport(new UserBadge($email));
}

public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
{
return null;
}

public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response
{
return new JsonResponse([
'error' => $exception->getMessageKey(),
], JsonResponse::HTTP_FORBIDDEN);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?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\Bundle\SecurityBundle\Tests\Functional\Bundle\AuthenticatorBundle;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class ProfileController extends AbstractController
{
public function __invoke()
{
$this->denyAccessUnlessGranted('ROLE_USER');

return $this->json(['email' => $this->getUser()->getUsername()]);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,6 @@ public function testFormLoginWithInvalidCsrfToken($options)
$client = $this->createClient($options);

$form = $client->request('GET', '/login')->selectButton('login')->form();
if ($options['enable_authenticator_manager'] ?? false) {
$form['user_login[username]'] = 'johannes';
$form['user_login[password]'] = 'test';
}
$form['user_login[_token]'] = '';
$client->submit($form);

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?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.
*/

return [
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
];
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
framework:
secret: test
router: { resource: "%kernel.project_dir%/%kernel.test_case%/routing.yml", utf8: true }
test: ~
default_locale: en
profiler: false
session:
storage_id: session.storage.mock_file

services:
logger: { class: Psr\Log\NullLogger }
Symfony\Bundle\SecurityBundle\Tests\Functional\Bundle\AuthenticatorBundle\ProfileController:
public: true
calls:
- ['setContainer', ['@Psr\Container\ContainerInterface']]
tags: [container.service_subscriber]
Symfony\Bundle\SecurityBundle\Tests\Functional\Bundle\AuthenticatorBundle\ApiAuthenticator: ~

security:
enable_authenticator_manager: true

encoders:
Symfony\Component\Security\Core\User\User: plaintext

providers:
in_memory:
memory:
users:
'jane@example.org': { password: test, roles: [ROLE_USER] }
in_memory2:
memory:
users:
'john@example.org': { password: test, roles: [ROLE_USER] }
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
imports:
- { resource: ./config.yml }

security:
firewalls:
api:
pattern: /
provider: in_memory
custom_authenticator: Symfony\Bundle\SecurityBundle\Tests\Functional\Bundle\AuthenticatorBundle\ApiAuthenticator

Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
imports:
- { resource: ./config.yml }

security:
firewalls:
api:
pattern: /
custom_authenticator: Symfony\Bundle\SecurityBundle\Tests\Functional\Bundle\AuthenticatorBundle\ApiAuthenticator

Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
profile:
path: /profile
defaults:
_controller: Symfony\Bundle\SecurityBundle\Tests\Functional\Bundle\AuthenticatorBundle\ProfileController
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Http\Authenticator\AuthenticatorInterface;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Credentials\PasswordCredentials;
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
use Symfony\Component\Security\Http\Authenticator\Passport\PassportInterface;
Expand Down Expand Up @@ -64,14 +65,13 @@ public function provideShouldNotCheckPassport()
$this->markTestSkipped('This test requires symfony/security-http:^5.1');
}

$user = new User('Wouter', null, ['ROLE_USER']);
// no LdapBadge
yield [new TestAuthenticator(), new Passport($user, new PasswordCredentials('s3cret'))];
yield [new TestAuthenticator(), new Passport(new UserBadge('test'), new PasswordCredentials('s3cret'))];

// ldap already resolved
$badge = new LdapBadge('app.ldap');
$badge->markResolved();
yield [new TestAuthenticator(), new Passport($user, new PasswordCredentials('s3cret'), [$badge])];
yield [new TestAuthenticator(), new Passport(new UserBadge('test'), new PasswordCredentials('s3cret'), [$badge])];
}

public function testPasswordCredentialsAlreadyResolvedThrowsException()
Expand All @@ -81,8 +81,7 @@ public function testPasswordCredentialsAlreadyResolvedThrowsException()

$badge = new PasswordCredentials('s3cret');
$badge->markResolved();
$user = new User('Wouter', null, ['ROLE_USER']);
$passport = new Passport($user, $badge, [new LdapBadge('app.ldap')]);
$passport = new Passport(new UserBadge('test'), $badge, [new LdapBadge('app.ldap')]);

$listener = $this->createListener();
$listener->onCheckPassport(new CheckPassportEvent(new TestAuthenticator(), $passport));
Expand Down Expand Up @@ -116,7 +115,7 @@ public function provideWrongPassportData()
}

// no password credentials
yield [new SelfValidatingPassport(new User('Wouter', null, ['ROLE_USER']), [new LdapBadge('app.ldap')])];
yield [new SelfValidatingPassport(new UserBadge('test'), [new LdapBadge('app.ldap')])];

// no user passport
$passport = $this->createMock(PassportInterface::class);
Expand Down Expand Up @@ -181,7 +180,7 @@ private function createEvent($password = 's3cr3t', $ldapBadge = null)
{
return new CheckPassportEvent(
new TestAuthenticator(),
new Passport(new User('Wouter', null, ['ROLE_USER']), new PasswordCredentials($password), [$ldapBadge ?? new LdapBadge('app.ldap')])
new Passport(new UserBadge('Wouter', function () { return new User('Wouter', null, ['ROLE_USER']); }), new PasswordCredentials($password), [$ldapBadge ?? new LdapBadge('app.ldap')])
);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
use Symfony\Component\Security\Http\Authenticator\InteractiveAuthenticatorInterface;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\PasswordUpgradeBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\RememberMeBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Credentials\CustomCredentials;
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
use Symfony\Component\Security\Http\Authenticator\Passport\PassportInterface;
Expand Down Expand Up @@ -62,14 +63,11 @@ public function authenticate(Request $request): PassportInterface
}

// get the user from the GuardAuthenticator
$user = $this->guard->getUser($credentials, $this->userProvider);

if (null === $user) {
throw new UsernameNotFoundException(sprintf('Null returned from "%s::getUser()".', get_debug_type($this->guard)));
}

if (!$user instanceof UserInterface) {
throw new \UnexpectedValueException(sprintf('The "%s::getUser()" method must return a UserInterface. You returned "%s".', get_debug_type($this->guard), get_debug_type($user)));
if (class_exists(UserBadge::class)) {
$user = new UserBadge('guard_authenticator_'.md5(serialize($credentials)), function () use ($credentials) { return $this->getUser($credentials); });
} else {
// BC with symfony/security-http:5.1
$user = $this->getUser($credentials);
}

$passport = new Passport($user, new CustomCredentials([$this->guard, 'checkCredentials'], $credentials));
Expand All @@ -84,6 +82,21 @@ public function authenticate(Request $request): PassportInterface
return $passport;
}

private function getUser($credentials): UserInterface
{
$user = $this->guard->getUser($credentials, $this->userProvider);

if (null === $user) {
throw new UsernameNotFoundException(sprintf('Null returned from "%s::getUser()".', get_debug_type($this->guard)));
}

if (!$user instanceof UserInterface) {
throw new \UnexpectedValueException(sprintf('The "%s::getUser()" method must return a UserInterface. You returned "%s".', get_debug_type($this->guard), get_debug_type($user)));
}

return $user;
}

public function createAuthenticatedToken(PassportInterface $passport, string $firewallName): TokenInterface
{
if (!$passport instanceof UserPassportInterface) {
Expand Down
Loading