feature #40443 [Security] Rename User to InMemoryUser (chalasr)

This PR was merged into the 5.3-dev branch.

Discussion
----------

[Security] Rename User to InMemoryUser

| Q             | A
| ------------- | ---
| Branch?       | 5.x
| Bug fix?      | no
| New feature?  | yes
| Deprecations? | yes
| Tickets       | Closes #26348
| License       | MIT
| Doc PR        | -

This PR aims to clarify that the `User` class should only be used by the `InMemoryUserProvider`, as documented:
c06a76c384/src/Symfony/Component/Security/Core/User/User.php (L15-L17)
It also renames `UserChecker` to `InMemoryUserChecker` because it only works with the in-memory user class:
c06a76c384/src/Symfony/Component/Security/Core/User/UserChecker.php (L31-L32)

Commits
-------

55b51d3f90 [Security] Rename User to InMemoryUser
This commit is contained in:
Fabien Potencier 2021-03-16 19:12:12 +01:00
commit db87d72869
69 changed files with 570 additions and 197 deletions

View File

@ -87,6 +87,10 @@ Routing
Security
--------
* Deprecate class `User`, use `InMemoryUser` or your own implementation instead.
If you are using the `isAccountNonLocked()`, `isAccountNonExpired()` or `isCredentialsNonExpired()` method, consider re-implementing
them in your own user class, as they are not part of the `InMemoryUser` API
* Deprecate class `UserChecker`, use `InMemoryUserChecker` or your own implementation instead
* Deprecate `UserInterface::getPassword()`
If your `getPassword()` method does not return `null` (i.e. you are using password-based authentication),
you should implement `PasswordAuthenticatedUserInterface`.

View File

@ -175,6 +175,10 @@ Routing
Security
--------
* Remove class `User`, use `InMemoryUser` or your own implementation instead.
If you are using the `isAccountNonLocked()`, `isAccountNonExpired()` or `isCredentialsNonExpired()` method, consider re-implementing them
in your own user class as they are not part of the `InMemoryUser` API
* Remove class `UserChecker`, use `InMemoryUserChecker` or your own implementation instead
* Remove `UserInterface::getPassword()`
If your `getPassword()` method does not return `null` (i.e. you are using password-based authentication),
you should implement `PasswordAuthenticatedUserInterface`.

View File

@ -38,15 +38,15 @@ use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\InMemoryUser;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\WebLink\Link;
use Twig\Environment;
@ -137,7 +137,7 @@ class AbstractControllerTest extends TestCase
public function testGetUser()
{
$user = new User('user', 'pass');
$user = new InMemoryUser('user', 'pass');
$token = new UsernamePasswordToken($user, 'pass', 'default', ['ROLE_USER']);
$controller = $this->createController();

View File

@ -11,7 +11,7 @@
namespace Symfony\Bundle\FrameworkBundle\Tests\Functional;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\InMemoryUser;
class SecurityTest extends AbstractWebTestCase
{
@ -20,7 +20,7 @@ class SecurityTest extends AbstractWebTestCase
*/
public function testLoginUser(string $username, array $roles, ?string $firewallContext)
{
$user = new User($username, 'the-password', $roles);
$user = new InMemoryUser($username, 'the-password', $roles);
$client = $this->createClient(['test_case' => 'Security', 'root_config' => 'config.yml']);
if (null === $firewallContext) {
@ -45,7 +45,7 @@ class SecurityTest extends AbstractWebTestCase
public function testLoginUserMultipleRequests()
{
$user = new User('the-username', 'the-password', ['ROLE_FOO']);
$user = new InMemoryUser('the-username', 'the-password', ['ROLE_FOO']);
$client = $this->createClient(['test_case' => 'Security', 'root_config' => 'config.yml']);
$client->loginUser($user);
@ -58,7 +58,7 @@ class SecurityTest extends AbstractWebTestCase
public function testLoginInBetweenRequests()
{
$user = new User('the-username', 'the-password', ['ROLE_FOO']);
$user = new InMemoryUser('the-username', 'the-password', ['ROLE_FOO']);
$client = $this->createClient(['test_case' => 'Security', 'root_config' => 'config.yml']);
$client->request('GET', '/main/user_profile');

View File

@ -73,7 +73,7 @@ Suppose that you have the following security configuration in your application:
# app/config/security.yml
security:
encoders:
Symfony\Component\Security\Core\User\User: plaintext
Symfony\Component\Security\Core\User\InMemoryUser: plaintext
App\Entity\User: auto
</comment>

View File

@ -41,9 +41,9 @@ use Symfony\Component\Security\Core\Role\RoleHierarchy;
use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\ChainUserProvider;
use Symfony\Component\Security\Core\User\InMemoryUserChecker;
use Symfony\Component\Security\Core\User\InMemoryUserProvider;
use Symfony\Component\Security\Core\User\MissingUserProvider;
use Symfony\Component\Security\Core\User\UserChecker;
use Symfony\Component\Security\Core\Validator\Constraints\UserPasswordValidator;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\Security\Http\Controller\UserValueResolver;
@ -126,7 +126,7 @@ return static function (ContainerConfigurator $container) {
->alias(UserPasswordEncoderInterface::class, 'security.password_encoder')
->deprecate('symfony/security-bundle', '5.3', 'The "%alias_id%" service is deprecated, use "'.UserPasswordHasherInterface::class.'" instead.')
->set('security.user_checker', UserChecker::class)
->set('security.user_checker', InMemoryUserChecker::class)
->set('security.expression_language', ExpressionLanguage::class)
->args([service('cache.security_expression_language')->nullOnInvalid()])

View File

@ -31,7 +31,7 @@ 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\User\UserChecker;
use Symfony\Component\Security\Core\User\InMemoryUserChecker;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
@ -626,7 +626,7 @@ class SecurityExtensionTest extends TestCase
public function provideUserCheckerConfig()
{
yield [[], UserChecker::class];
yield [[], InMemoryUserChecker::class];
yield [['user_checker' => TestUserChecker::class], TestUserChecker::class];
}

View File

@ -17,7 +17,7 @@ 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\Core\User\User;
use Symfony\Component\Security\Core\User\InMemoryUser;
use Symfony\Component\Security\Http\Authenticator\AbstractAuthenticator;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\PassportInterface;
@ -46,7 +46,7 @@ class ApiAuthenticator extends AbstractAuthenticator
$userLoader = null;
if ($this->selfLoadingUser) {
$userLoader = function ($username) { return new User($username, 'test', ['ROLE_USER']); };
$userLoader = function ($username) { return new InMemoryUser($username, 'test', ['ROLE_USER']); };
}
return new SelfValidatingPassport(new UserBadge($email, $userLoader));

View File

@ -13,7 +13,7 @@ namespace Symfony\Bundle\SecurityBundle\Tests\Functional\Bundle\GuardedBundle;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\InMemoryUser;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Guard\GuardAuthenticatorHandler;
use Symfony\Component\Security\Guard\Token\PostAuthenticationGuardToken;
@ -22,7 +22,7 @@ class AuthenticationController
{
public function manualLoginAction(GuardAuthenticatorHandler $guardAuthenticatorHandler, Request $request)
{
$guardAuthenticatorHandler->authenticateWithToken(new PostAuthenticationGuardToken(new User('Jane', 'test', ['ROLE_USER']), 'secure', ['ROLE_USER']), $request, 'secure');
$guardAuthenticatorHandler->authenticateWithToken(new PostAuthenticationGuardToken(new InMemoryUser('Jane', 'test', ['ROLE_USER']), 'secure', ['ROLE_USER']), $request, 'secure');
return new Response('Logged in.');
}

View File

@ -5,7 +5,7 @@ namespace Symfony\Bundle\SecurityBundle\Tests\Functional\Bundle\SecuredPageBundl
use Symfony\Bundle\SecurityBundle\Tests\Functional\UserWithoutEquatable;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\InMemoryUser;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
@ -52,11 +52,11 @@ class ArrayUserProvider implements UserProviderInterface
$storedUser = $this->getUser($user->getUsername());
$class = \get_class($storedUser);
return new $class($storedUser->getUsername(), $storedUser->getPassword(), $storedUser->getRoles(), $storedUser->isEnabled(), $storedUser->isAccountNonExpired(), $storedUser->isCredentialsNonExpired() && $storedUser->getPassword() === $user->getPassword(), $storedUser->isAccountNonLocked());
return new $class($storedUser->getUsername(), $storedUser->getPassword(), $storedUser->getRoles(), $storedUser->isEnabled());
}
public function supportsClass($class)
{
return User::class === $class || UserWithoutEquatable::class === $class;
return InMemoryUser::class === $class || UserWithoutEquatable::class === $class;
}
}

View File

@ -12,8 +12,8 @@
namespace Symfony\Bundle\SecurityBundle\Tests\Functional;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\User\InMemoryUser;
use Symfony\Component\Security\Core\User\InMemoryUserProvider;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
@ -73,7 +73,7 @@ class RememberMeUserProvider implements UserProviderInterface
{
$user = $this->inner->refreshUser($user);
$alterUser = \Closure::bind(function (User $user) { $user->password = 'foo'; }, null, User::class);
$alterUser = \Closure::bind(function (InMemoryUser $user) { $user->password = 'foo'; }, null, InMemoryUser::class);
$alterUser($user);
return $user;

View File

@ -13,7 +13,7 @@ namespace Symfony\Bundle\SecurityBundle\Tests\Functional;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\InMemoryUser;
use Symfony\Component\Security\Http\LoginLink\LoginLinkHandler;
use Symfony\Component\Security\Http\LoginLink\LoginLinkHandlerInterface;
@ -36,7 +36,7 @@ class LoginLinkAuthenticationTest extends AbstractWebTestCase
/** @var LoginLinkHandlerInterface $loginLinkHandler */
$loginLinkHandler = self::getContainer()->get(LoginLinkHandlerInterface::class);
$user = new User('weaverryan', 'foo');
$user = new InMemoryUser('weaverryan', 'foo');
$loginLink = $loginLinkHandler->createLoginLink($user);
$this->assertStringContainsString('user=weaverryan', $loginLink);
$this->assertStringContainsString('hash=', $loginLink);

View File

@ -13,8 +13,8 @@ namespace Symfony\Bundle\SecurityBundle\Tests\Functional;
use Symfony\Bundle\SecurityBundle\Tests\Functional\Bundle\SecuredPageBundle\Security\Core\User\ArrayUserProvider;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\User\InMemoryUser;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\UserInterface;
class SecurityTest extends AbstractWebTestCase
@ -26,7 +26,7 @@ class SecurityTest extends AbstractWebTestCase
$container = $kernel->getContainer();
// put a token into the storage so the final calls can function
$user = new User('foo', 'pass');
$user = new InMemoryUser('foo', 'pass');
$token = new UsernamePasswordToken($user, '', 'provider', ['ROLE_USER']);
$container->get('security.token_storage')->setToken($token);
@ -39,8 +39,8 @@ class SecurityTest extends AbstractWebTestCase
{
return [
[
new User('user1', 'test', ['ROLE_ADMIN']),
new User('user1', 'test', ['ROLE_USER']),
new InMemoryUser('user1', 'test', ['ROLE_ADMIN']),
new InMemoryUser('user1', 'test', ['ROLE_USER']),
],
[
new UserWithoutEquatable('user1', 'test', ['ROLE_ADMIN']),

View File

@ -19,6 +19,7 @@ use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface;
use Symfony\Component\Security\Core\Encoder\NativePasswordEncoder;
use Symfony\Component\Security\Core\Encoder\Pbkdf2PasswordEncoder;
use Symfony\Component\Security\Core\Encoder\SodiumPasswordEncoder;
use Symfony\Component\Security\Core\User\InMemoryUser;
/**
* Tests UserPasswordEncoderCommand.
@ -36,7 +37,7 @@ class UserPasswordEncoderCommandTest extends AbstractWebTestCase
$this->passwordEncoderCommandTester->execute([
'command' => 'security:encode-password',
'password' => 'password',
'user-class' => 'Symfony\Component\Security\Core\User\User',
'user-class' => InMemoryUser::class,
'--empty-salt' => true,
], ['decorated' => false]);
$expected = str_replace("\n", \PHP_EOL, file_get_contents(__DIR__.'/app/PasswordEncode/emptysalt.txt'));
@ -189,7 +190,7 @@ class UserPasswordEncoderCommandTest extends AbstractWebTestCase
$this->passwordEncoderCommandTester->execute([
'command' => 'security:encode-password',
'password' => 'p@ssw0rd',
'user-class' => 'Symfony\Component\Security\Core\User\User',
'user-class' => InMemoryUser::class,
'--empty-salt' => true,
]);
@ -282,7 +283,7 @@ class UserPasswordEncoderCommandTest extends AbstractWebTestCase
[0] Custom\Class\Native\User
[1] Custom\Class\Pbkdf2\User
[2] Custom\Class\Test\User
[3] Symfony\Component\Security\Core\User\User
[3] Symfony\Component\Security\Core\User\InMemoryUser
EOTXT
, $this->passwordEncoderCommandTester->getDisplay(true));
}

View File

@ -2,7 +2,7 @@ security:
enable_authenticator_manager: true
password_hashers:
Symfony\Component\Security\Core\User\User: plaintext
Symfony\Component\Security\Core\User\InMemoryUser: plaintext
providers:
in_memory:

View File

@ -3,7 +3,7 @@ imports:
security:
password_hashers:
Symfony\Component\Security\Core\User\User: plaintext
Symfony\Component\Security\Core\User\InMemoryUser: plaintext
providers:
in_memory:

View File

@ -16,7 +16,7 @@ services:
security:
password_hashers:
Symfony\Component\Security\Core\User\User: plaintext
Symfony\Component\Security\Core\User\InMemoryUser: plaintext
providers:
in_memory:

View File

@ -29,4 +29,4 @@ security:
users:
john: { password: doe, roles: [ROLE_SECURE] }
password_hashers:
Symfony\Component\Security\Core\User\User: plaintext
Symfony\Component\Security\Core\User\InMemoryUser: plaintext

View File

@ -15,7 +15,7 @@ services:
security:
password_hashers:
Symfony\Component\Security\Core\User\User: plaintext
Symfony\Component\Security\Core\User\InMemoryUser: plaintext
providers:
in_memory:

View File

@ -6,7 +6,7 @@ framework:
security:
password_hashers:
Symfony\Component\Security\Core\User\User: plaintext
Symfony\Component\Security\Core\User\InMemoryUser: plaintext
providers:
in_memory:

View File

@ -3,7 +3,7 @@ imports:
security:
password_hashers:
Symfony\Component\Security\Core\User\User: plaintext
Symfony\Component\Security\Core\User\InMemoryUser: plaintext
providers:
in_memory:

View File

@ -3,7 +3,7 @@ imports:
security:
password_hashers:
Symfony\Component\Security\Core\User\User: plaintext
Symfony\Component\Security\Core\User\InMemoryUser: plaintext
providers:
in_memory:

View File

@ -3,7 +3,7 @@ imports:
security:
password_hashers:
Symfony\Component\Security\Core\User\User: plaintext
Symfony\Component\Security\Core\User\InMemoryUser: plaintext
providers:
in_memory:

View File

@ -3,7 +3,7 @@ imports:
security:
password_hashers:
Symfony\Component\Security\Core\User\User: plaintext
Symfony\Component\Security\Core\User\InMemoryUser: plaintext
providers:
in_memory:

View File

@ -3,7 +3,7 @@ imports:
security:
encoders:
Symfony\Component\Security\Core\User\User: plaintext
Symfony\Component\Security\Core\User\InMemoryUser: plaintext
Custom\Class\Native\User:
algorithm: native
cost: 10

View File

@ -9,7 +9,7 @@ framework:
security:
password_hashers:
Symfony\Component\Security\Core\User\User: plaintext
Symfony\Component\Security\Core\User\InMemoryUser: plaintext
providers:
in_memory:

View File

@ -7,7 +7,7 @@ parameters:
security:
password_hashers:
Symfony\Component\Security\Core\User\User: plaintext
Symfony\Component\Security\Core\User\InMemoryUser: plaintext
providers:
in_memory:

View File

@ -3,7 +3,7 @@ imports:
security:
password_hashers:
Symfony\Component\Security\Core\User\User: plaintext
Symfony\Component\Security\Core\User\InMemoryUser: plaintext
providers:
in_memory:

View File

@ -3,7 +3,7 @@ imports:
security:
password_hashers:
Symfony\Component\Security\Core\User\User: plaintext
Symfony\Component\Security\Core\User\InMemoryUser: plaintext
providers:
in_memory:

View File

@ -3,7 +3,7 @@ imports:
security:
password_hashers:
Symfony\Component\Security\Core\User\User: plaintext
Symfony\Component\Security\Core\User\InMemoryUser: plaintext
providers:
in_memory:

View File

@ -25,7 +25,7 @@ use Symfony\Component\Ldap\Security\LdapBadge;
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\Core\User\User;
use Symfony\Component\Security\Core\User\InMemoryUser;
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;
@ -188,7 +188,7 @@ class CheckLdapCredentialsListenerTest extends TestCase
{
return new CheckPassportEvent(
new TestAuthenticator(),
new Passport(new UserBadge('Wouter', function () { return new User('Wouter', null, ['ROLE_USER']); }), new PasswordCredentials($password), [$ldapBadge ?? new LdapBadge('app.ldap')])
new Passport(new UserBadge('Wouter', function () { return new InMemoryUser('Wouter', null, ['ROLE_USER']); }), new PasswordCredentials($password), [$ldapBadge ?? new LdapBadge('app.ldap')])
);
}

View File

@ -71,7 +71,7 @@ Suppose that you have the following security configuration in your application:
# app/config/security.yml
security:
password_hashers:
Symfony\Component\Security\Core\User\User: plaintext
Symfony\Component\Security\Core\User\InMemoryUser: plaintext
App\Entity\User: auto
</comment>

View File

@ -19,7 +19,7 @@ use Symfony\Component\PasswordHasher\Hasher\PasswordHasherFactory;
use Symfony\Component\PasswordHasher\Hasher\PasswordHasherFactoryInterface;
use Symfony\Component\PasswordHasher\Hasher\Pbkdf2PasswordHasher;
use Symfony\Component\PasswordHasher\Hasher\SodiumPasswordHasher;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\InMemoryUser;
class UserPasswordHashCommandTest extends TestCase
{
@ -30,7 +30,7 @@ class UserPasswordHashCommandTest extends TestCase
{
$this->passwordHasherCommandTester->execute([
'password' => 'password',
'user-class' => 'Symfony\Component\Security\Core\User\User',
'user-class' => 'Symfony\Component\Security\Core\User\InMemoryUser',
'--empty-salt' => true,
], ['decorated' => false]);
@ -173,7 +173,7 @@ class UserPasswordHashCommandTest extends TestCase
{
$this->passwordHasherCommandTester->execute([
'password' => 'p@ssw0rd',
'user-class' => 'Symfony\Component\Security\Core\User\User',
'user-class' => 'Symfony\Component\Security\Core\User\InMemoryUser',
'--empty-salt' => true,
]);
@ -260,7 +260,7 @@ class UserPasswordHashCommandTest extends TestCase
[0] Custom\Class\Native\User
[1] Custom\Class\Pbkdf2\User
[2] Custom\Class\Test\User
[3] Symfony\Component\Security\Core\User\User
[3] Symfony\Component\Security\Core\User\InMemoryUser
EOTXT
, $this->passwordHasherCommandTester->getDisplay(true));
}
@ -289,7 +289,7 @@ EOTXT
{
putenv('COLUMNS='.(119 + \strlen(\PHP_EOL)));
$hasherFactory = new PasswordHasherFactory([
User::class => ['algorithm' => 'plaintext'],
InMemoryUser::class => ['algorithm' => 'plaintext'],
'Custom\Class\Native\User' => ['algorithm' => 'native', 'cost' => 10],
'Custom\Class\Pbkdf2\User' => ['algorithm' => 'pbkdf2', 'hash_algorithm' => 'sha512', 'iterations' => 1000, 'encode_as_base64' => true],
'Custom\Class\Test\User' => ['algorithm' => 'test'],
@ -297,7 +297,7 @@ EOTXT
$this->passwordHasherCommandTester = new CommandTester(new UserPasswordHashCommand(
$hasherFactory,
[User::class, 'Custom\Class\Native\User', 'Custom\Class\Pbkdf2\User', 'Custom\Class\Test\User']
[InMemoryUser::class, 'Custom\Class\Native\User', 'Custom\Class\Pbkdf2\User', 'Custom\Class\Test\User']
));
}
@ -342,7 +342,7 @@ EOTXT
$this->passwordHasherCommandTester = new CommandTester(new UserPasswordHashCommand(
$hasherFactory,
[User::class, 'Custom\Class\Pbkdf2\User', 'Custom\Class\Test\User']
[InMemoryUser::class, 'Custom\Class\Pbkdf2\User', 'Custom\Class\Test\User']
));
}

View File

@ -18,7 +18,7 @@ use Symfony\Component\PasswordHasher\Hasher\NativePasswordHasher;
use Symfony\Component\PasswordHasher\Hasher\PasswordHasherAwareInterface;
use Symfony\Component\PasswordHasher\Hasher\PasswordHasherFactory;
use Symfony\Component\PasswordHasher\Hasher\SodiumPasswordHasher;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\InMemoryUser;
use Symfony\Component\Security\Core\User\UserInterface;
class PasswordHasherFactoryTest extends TestCase
@ -46,7 +46,7 @@ class PasswordHasherFactoryTest extends TestCase
$expectedHasher = new MessageDigestPasswordHasher('sha1');
$this->assertEquals($expectedHasher->hash('foo', ''), $hasher->hash('foo', ''));
$hasher = $factory->getPasswordHasher(new User('user', 'pass'));
$hasher = $factory->getPasswordHasher(new InMemoryUser('user', 'pass'));
$expectedHasher = new MessageDigestPasswordHasher('sha1');
$this->assertEquals($expectedHasher->hash('foo', ''), $hasher->hash('foo', ''));
}
@ -65,10 +65,10 @@ class PasswordHasherFactoryTest extends TestCase
public function testGetHasherConfiguredForConcreteClassWithService()
{
$factory = new PasswordHasherFactory([
'Symfony\Component\Security\Core\User\User' => new MessageDigestPasswordHasher('sha1'),
'Symfony\Component\Security\Core\User\InMemoryUser' => new MessageDigestPasswordHasher('sha1'),
]);
$hasher = $factory->getPasswordHasher(new User('user', 'pass'));
$hasher = $factory->getPasswordHasher(new InMemoryUser('user', 'pass'));
$expectedHasher = new MessageDigestPasswordHasher('sha1');
$this->assertEquals($expectedHasher->hash('foo', ''), $hasher->hash('foo', ''));
}

View File

@ -17,8 +17,8 @@ use Symfony\Component\PasswordHasher\Hasher\NativePasswordHasher;
use Symfony\Component\PasswordHasher\Hasher\PasswordHasherFactoryInterface;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasher;
use Symfony\Component\PasswordHasher\PasswordHasherInterface;
use Symfony\Component\Security\Core\User\InMemoryUser;
use Symfony\Component\Security\Core\User\LegacyPasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\UserInterface;
class UserPasswordHasherTest extends TestCase
@ -110,7 +110,7 @@ class UserPasswordHasherTest extends TestCase
public function testNeedsRehash()
{
$user = new User('username', null);
$user = new InMemoryUser('username', null);
$hasher = new NativePasswordHasher(4, 20000, 4);
$mockPasswordHasherFactory = $this->createMock(PasswordHasherFactoryInterface::class);
@ -121,7 +121,7 @@ class UserPasswordHasherTest extends TestCase
$passwordHasher = new UserPasswordHasher($mockPasswordHasherFactory);
$user->setPassword($passwordHasher->hashPassword($user, 'foo', 'salt'));
\Closure::bind(function () use ($passwordHasher) { $this->password = $passwordHasher->hashPassword($this, 'foo', 'salt'); }, $user, InMemoryUser::class)();
$this->assertFalse($passwordHasher->needsRehash($user));
$this->assertTrue($passwordHasher->needsRehash($user));
$this->assertFalse($passwordHasher->needsRehash($user));

View File

@ -4,6 +4,8 @@ CHANGELOG
5.3
---
* Deprecate class `User`, use `InMemoryUser` instead
* Deprecate class `UserChecker`, use `InMemoryUserChecker` or your own implementation instead
* Add `PasswordAuthenticatedUserInterface` for user classes that use passwords
* Add `LegacyPasswordAuthenticatedUserInterface` for user classes that use user-provided salts in addition to passwords
* Deprecate all classes in the `Core\Encoder\` sub-namespace, use the `PasswordHasher` component instead

View File

@ -21,8 +21,8 @@ use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationServiceException;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\User\InMemoryUser;
use Symfony\Component\Security\Core\User\PasswordUpgraderInterface;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
@ -174,7 +174,7 @@ class DaoAuthenticationProviderTest extends TestCase
$method->invoke(
$provider,
new User('username', 'password'),
new InMemoryUser('username', 'password'),
$token
);
}
@ -198,7 +198,7 @@ class DaoAuthenticationProviderTest extends TestCase
->willReturn('foo')
;
$method->invoke($provider, new User('username', 'password'), $token);
$method->invoke($provider, new InMemoryUser('username', 'password'), $token);
}
public function testCheckAuthenticationDoesNotReauthenticateWhenPasswordHasChanged()
@ -270,12 +270,12 @@ class DaoAuthenticationProviderTest extends TestCase
->willReturn('foo')
;
$method->invoke($provider, new User('username', 'password'), $token);
$method->invoke($provider, new InMemoryUser('username', 'password'), $token);
}
public function testPasswordUpgrades()
{
$user = new User('user', 'pwd');
$user = new InMemoryUser('user', 'pwd');
$hasher = $this->createMock(PasswordHasherInterface::class);
$hasher->expects($this->once())

View File

@ -20,7 +20,7 @@ use Symfony\Component\Ldap\LdapInterface;
use Symfony\Component\Security\Core\Authentication\Provider\LdapBindAuthenticationProvider;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\InMemoryUser;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
@ -41,7 +41,7 @@ class LdapBindAuthenticationProviderTest extends TestCase
$reflection = new \ReflectionMethod($provider, 'checkAuthentication');
$reflection->setAccessible(true);
$reflection->invoke($provider, new User('foo', null), new UsernamePasswordToken('foo', '', 'key'));
$reflection->invoke($provider, new InMemoryUser('foo', null), new UsernamePasswordToken('foo', '', 'key'));
}
public function testNullPasswordShouldThrowAnException()
@ -56,7 +56,7 @@ class LdapBindAuthenticationProviderTest extends TestCase
$reflection = new \ReflectionMethod($provider, 'checkAuthentication');
$reflection->setAccessible(true);
$reflection->invoke($provider, new User('foo', null), new UsernamePasswordToken('foo', null, 'key'));
$reflection->invoke($provider, new InMemoryUser('foo', null), new UsernamePasswordToken('foo', null, 'key'));
}
public function testBindFailureShouldThrowAnException()
@ -76,7 +76,7 @@ class LdapBindAuthenticationProviderTest extends TestCase
$reflection = new \ReflectionMethod($provider, 'checkAuthentication');
$reflection->setAccessible(true);
$reflection->invoke($provider, new User('foo', null), new UsernamePasswordToken('foo', 'bar', 'key'));
$reflection->invoke($provider, new InMemoryUser('foo', null), new UsernamePasswordToken('foo', 'bar', 'key'));
}
public function testRetrieveUser()
@ -136,7 +136,7 @@ class LdapBindAuthenticationProviderTest extends TestCase
$reflection = new \ReflectionMethod($provider, 'checkAuthentication');
$reflection->setAccessible(true);
$reflection->invoke($provider, new User('foo', null), new UsernamePasswordToken('foo', 'bar', 'key'));
$reflection->invoke($provider, new InMemoryUser('foo', null), new UsernamePasswordToken('foo', 'bar', 'key'));
}
public function testQueryWithUserForDn()
@ -178,7 +178,7 @@ class LdapBindAuthenticationProviderTest extends TestCase
$reflection = new \ReflectionMethod($provider, 'checkAuthentication');
$reflection->setAccessible(true);
$reflection->invoke($provider, new User('foo', null), new UsernamePasswordToken('foo', 'bar', 'key'));
$reflection->invoke($provider, new InMemoryUser('foo', null), new UsernamePasswordToken('foo', 'bar', 'key'));
}
public function testEmptyQueryResultShouldThrowAnException()
@ -214,6 +214,6 @@ class LdapBindAuthenticationProviderTest extends TestCase
$reflection = new \ReflectionMethod($provider, 'checkAuthentication');
$reflection->setAccessible(true);
$reflection->invoke($provider, new User('foo', null), new UsernamePasswordToken('foo', 'bar', 'key'));
$reflection->invoke($provider, new InMemoryUser('foo', null), new UsernamePasswordToken('foo', 'bar', 'key'));
}
}

View File

@ -19,7 +19,7 @@ use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\Exception\DisabledException;
use Symfony\Component\Security\Core\Exception\LogicException;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\InMemoryUser;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Core\User\UserInterface;
@ -59,7 +59,7 @@ class RememberMeAuthenticationProviderTest extends TestCase
$this->expectExceptionMessage('Method "Symfony\Component\Security\Core\Authentication\Token\RememberMeToken::getUser()" must return a "Symfony\Component\Security\Core\User\UserInterface" instance, "string" returned.');
$provider = $this->getProvider();
$token = new RememberMeToken(new User('dummyuser', null), 'foo', 'test');
$token = new RememberMeToken(new InMemoryUser('dummyuser', null), 'foo', 'test');
$token->setUser('stringish-user');
$provider->authenticate($token);
}

View File

@ -23,7 +23,7 @@ use Symfony\Component\Security\Core\Authorization\AuthorizationChecker;
use Symfony\Component\Security\Core\Authorization\ExpressionLanguage;
use Symfony\Component\Security\Core\Authorization\Voter\AuthenticatedVoter;
use Symfony\Component\Security\Core\Authorization\Voter\RoleVoter;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\InMemoryUser;
class ExpressionLanguageTest extends TestCase
{
@ -49,7 +49,7 @@ class ExpressionLanguageTest extends TestCase
public function provider()
{
$roles = ['ROLE_USER', 'ROLE_ADMIN'];
$user = new User('username', 'password', $roles);
$user = new InMemoryUser('username', 'password', $roles);
$noToken = null;
$anonymousToken = new AnonymousToken('firewall', 'anon.');

View File

@ -18,7 +18,7 @@ use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\InMemoryUser;
class SecurityTest extends TestCase
{
@ -66,7 +66,7 @@ class SecurityTest extends TestCase
yield [new StringishUser(), null];
$user = new User('nice_user', 'foo');
$user = new InMemoryUser('nice_user', 'foo');
yield [$user, $user];
}

View File

@ -15,9 +15,9 @@ use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\User\ChainUserProvider;
use Symfony\Component\Security\Core\User\InMemoryUser;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\PasswordUpgraderInterface;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
@ -250,7 +250,7 @@ class ChainUserProviderTest extends TestCase
public function testPasswordUpgrades()
{
$user = new User('user', 'pwd');
$user = new InMemoryUser('user', 'pwd');
$provider1 = $this->getMockForAbstractClass(MigratingProvider::class);
$provider1

View File

@ -0,0 +1,41 @@
<?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\Core\Tests\User;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Exception\DisabledException;
use Symfony\Component\Security\Core\User\InMemoryUser;
use Symfony\Component\Security\Core\User\InMemoryUserChecker;
use Symfony\Component\Security\Core\User\UserInterface;
class InMemoryUserCheckerTest extends TestCase
{
public function testCheckPostAuthNotAdvancedUserInterface()
{
$checker = new InMemoryUserChecker();
$this->assertNull($checker->checkPostAuth($this->createMock(UserInterface::class)));
}
public function testCheckPostAuthPass()
{
$checker = new InMemoryUserChecker();
$this->assertNull($checker->checkPostAuth(new InMemoryUser('John', 'password')));
}
public function testCheckPreAuthDisabled()
{
$this->expectException(DisabledException::class);
$checker = new InMemoryUserChecker();
$checker->checkPreAuth(new InMemoryUser('John', 'password', [], false));
}
}

View File

@ -12,12 +12,16 @@
namespace Symfony\Component\Security\Core\Tests\User;
use PHPUnit\Framework\TestCase;
use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\User\InMemoryUser;
use Symfony\Component\Security\Core\User\InMemoryUserProvider;
use Symfony\Component\Security\Core\User\User;
class InMemoryUserProviderTest extends TestCase
{
use ExpectDeprecationTrait;
public function testConstructor()
{
$provider = $this->createProvider();
@ -29,6 +33,21 @@ class InMemoryUserProviderTest extends TestCase
}
public function testRefresh()
{
$user = new InMemoryUser('fabien', 'bar');
$provider = $this->createProvider();
$refreshedUser = $provider->refreshUser($user);
$this->assertEquals('foo', $refreshedUser->getPassword());
$this->assertEquals(['ROLE_USER'], $refreshedUser->getRoles());
$this->assertFalse($refreshedUser->isEnabled());
}
/**
* @group legacy
*/
public function testRefreshWithLegacyUser()
{
$user = new User('fabien', 'bar');

View File

@ -0,0 +1,105 @@
<?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\Core\Tests\User;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\User\EquatableInterface;
use Symfony\Component\Security\Core\User\InMemoryUser;
use Symfony\Component\Security\Core\User\UserInterface;
class InMemoryUserTest extends TestCase
{
public function testConstructorException()
{
$this->expectException(\InvalidArgumentException::class);
new InMemoryUser('', 'superpass');
}
public function testGetRoles()
{
$user = new InMemoryUser('fabien', 'superpass');
$this->assertEquals([], $user->getRoles());
$user = new InMemoryUser('fabien', 'superpass', ['ROLE_ADMIN']);
$this->assertEquals(['ROLE_ADMIN'], $user->getRoles());
}
public function testGetPassword()
{
$user = new InMemoryUser('fabien', 'superpass');
$this->assertEquals('superpass', $user->getPassword());
}
public function testGetUsername()
{
$user = new InMemoryUser('fabien', 'superpass');
$this->assertEquals('fabien', $user->getUsername());
}
public function testGetSalt()
{
$user = new InMemoryUser('fabien', 'superpass');
$this->assertNull($user->getSalt());
}
public function testIsEnabled()
{
$user = new InMemoryUser('mathilde', 'k');
$this->assertTrue($user->isEnabled());
$user = new InMemoryUser('robin', 'superpass', [], false);
$this->assertFalse($user->isEnabled());
}
public function testEraseCredentials()
{
$user = new InMemoryUser('fabien', 'superpass');
$user->eraseCredentials();
$this->assertEquals('superpass', $user->getPassword());
}
public function testToString()
{
$user = new InMemoryUser('fabien', 'superpass');
$this->assertEquals('fabien', (string) $user);
}
/**
* @dataProvider isEqualToData
*
* @param bool $expectation
* @param EquatableInterface|UserInterface $a
* @param EquatableInterface|UserInterface $b
*/
public function testIsEqualTo($expectation, $a, $b)
{
$this->assertSame($expectation, $a->isEqualTo($b));
$this->assertSame($expectation, $b->isEqualTo($a));
}
public static function isEqualToData()
{
return [
[true, new InMemoryUser('username', 'password'), new InMemoryUser('username', 'password')],
[false, new InMemoryUser('username', 'password', ['ROLE']), new InMemoryUser('username', 'password')],
[false, new InMemoryUser('username', 'password', ['ROLE']), new InMemoryUser('username', 'password', ['NO ROLE'])],
[false, new InMemoryUser('diff', 'diff'), new InMemoryUser('username', 'password')],
[false, new InMemoryUser('diff', 'diff', [], false), new InMemoryUser('username', 'password')],
];
}
public function testIsEqualToWithDifferentUser()
{
$user = new InMemoryUser('username', 'password');
$this->assertFalse($user->isEqualTo($this->createMock(UserInterface::class)));
}
}

View File

@ -20,6 +20,9 @@ use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\UserChecker;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* @group legacy
*/
class UserCheckerTest extends TestCase
{
public function testCheckPostAuthNotAdvancedUserInterface()

View File

@ -16,6 +16,9 @@ use Symfony\Component\Security\Core\User\EquatableInterface;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* @group legacy
*/
class UserTest extends TestCase
{
public function testConstructorException()

View File

@ -0,0 +1,133 @@
<?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\Core\User;
/**
* UserInterface implementation used by the in-memory user provider.
*
* This should not be used for anything else.
*
* @author Robin Chalas <robin.chalas@gmail.com>
* @author Fabien Potencier <fabien@symfony.com>
*/
final class InMemoryUser implements UserInterface, PasswordAuthenticatedUserInterface, EquatableInterface
{
private $username;
private $password;
private $enabled;
private $roles;
/**
* @param string[] $roles
*/
public function __construct(string $username, ?string $password, array $roles = [], bool $enabled = true)
{
if ('' === $username) {
throw new \InvalidArgumentException('The username cannot be empty.');
}
$this->username = $username;
$this->password = $password;
$this->roles = $roles;
$this->enabled = $enabled;
}
public function __toString(): string
{
return $this->getUsername();
}
/**
* {@inheritdoc}
*/
public function getRoles(): array
{
return $this->roles;
}
/**
* {@inheritdoc}
*/
public function getPassword(): ?string
{
return $this->password;
}
/**
* {@inheritdoc}
*/
public function getSalt(): ?string
{
return null;
}
/**
* {@inheritdoc}
*/
public function getUsername(): string
{
return $this->username;
}
/**
* Checks whether the user is enabled.
*
* Internally, if this method returns false, the authentication system
* will throw a DisabledException and prevent login.
*
* @return bool true if the user is enabled, false otherwise
*
* @see DisabledException
*/
public function isEnabled(): bool
{
return $this->enabled;
}
/**
* {@inheritdoc}
*/
public function eraseCredentials()
{
}
/**
* {@inheritdoc}
*/
public function isEqualTo(UserInterface $user): bool
{
if (!$user instanceof self) {
return false;
}
if ($this->getPassword() !== $user->getPassword()) {
return false;
}
$currentRoles = array_map('strval', (array) $this->getRoles());
$newRoles = array_map('strval', (array) $user->getRoles());
$rolesChanged = \count($currentRoles) !== \count($newRoles) || \count($currentRoles) !== \count(array_intersect($currentRoles, $newRoles));
if ($rolesChanged) {
return false;
}
if ($this->getUsername() !== $user->getUsername()) {
return false;
}
if ($this->isEnabled() !== $user->isEnabled()) {
return false;
}
return true;
}
}

View File

@ -0,0 +1,70 @@
<?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\Core\User;
use Symfony\Component\Security\Core\Exception\AccountExpiredException;
use Symfony\Component\Security\Core\Exception\CredentialsExpiredException;
use Symfony\Component\Security\Core\Exception\DisabledException;
use Symfony\Component\Security\Core\Exception\LockedException;
/**
* Checks the state of the in-memory user account.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class InMemoryUserChecker implements UserCheckerInterface
{
public function checkPreAuth(UserInterface $user)
{
// @deprecated since Symfony 5.3, in 6.0 change to:
// if (!$user instanceof InMemoryUser) {
if (!$user instanceof InMemoryUser && !$user instanceof User) {
return;
}
if (!$user->isEnabled()) {
$ex = new DisabledException('User account is disabled.');
$ex->setUser($user);
throw $ex;
}
// @deprecated since Symfony 5.3
if ($user instanceof User) {
if (!$user->isAccountNonLocked()) {
$ex = new LockedException('User account is locked.');
$ex->setUser($user);
throw $ex;
}
if (!$user->isAccountNonExpired()) {
$ex = new AccountExpiredException('User account has expired.');
$ex->setUser($user);
throw $ex;
}
}
}
public function checkPostAuth(UserInterface $user)
{
// @deprecated since Symfony 5.3, noop in 6.0
if (!$user instanceof User) {
return;
}
if (!$user->isCredentialsNonExpired()) {
$ex = new CredentialsExpiredException('User credentials have expired.');
$ex->setUser($user);
throw $ex;
}
}
}
class_alias(InMemoryUserChecker::class, UserChecker::class);

View File

@ -38,7 +38,7 @@ class InMemoryUserProvider implements UserProviderInterface
$password = $attributes['password'] ?? null;
$enabled = $attributes['enabled'] ?? true;
$roles = $attributes['roles'] ?? [];
$user = new User($username, $password, $roles, $enabled, true, true, true);
$user = new InMemoryUser($username, $password, $roles, $enabled);
$this->createUser($user);
}
@ -65,7 +65,7 @@ class InMemoryUserProvider implements UserProviderInterface
{
$user = $this->getUser($username);
return new User($user->getUsername(), $user->getPassword(), $user->getRoles(), $user->isEnabled(), $user->isAccountNonExpired(), $user->isCredentialsNonExpired(), $user->isAccountNonLocked());
return new InMemoryUser($user->getUsername(), $user->getPassword(), $user->getRoles(), $user->isEnabled());
}
/**
@ -73,13 +73,28 @@ class InMemoryUserProvider implements UserProviderInterface
*/
public function refreshUser(UserInterface $user)
{
if (!$user instanceof User) {
if (!$user instanceof InMemoryUser && !$user instanceof User) {
throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_debug_type($user)));
}
$storedUser = $this->getUser($user->getUsername());
return new User($storedUser->getUsername(), $storedUser->getPassword(), $storedUser->getRoles(), $storedUser->isEnabled(), $storedUser->isAccountNonExpired(), $storedUser->isCredentialsNonExpired() && $storedUser->getPassword() === $user->getPassword(), $storedUser->isAccountNonLocked());
// @deprecated since Symfony 5.3
if ($user instanceof User) {
if (!$storedUser instanceof User) {
$accountNonExpired = true;
$credentialsNonExpired = $storedUser->getPassword() === $user->getPassword();
$accountNonLocked = true;
} else {
$accountNonExpired = $storedUser->isAccountNonExpired();
$credentialsNonExpired = $storedUser->isCredentialsNonExpired() && $storedUser->getPassword() === $user->getPassword();
$accountNonLocked = $storedUser->isAccountNonLocked();
}
return new User($storedUser->getUsername(), $storedUser->getPassword(), $storedUser->getRoles(), $storedUser->isEnabled(), $accountNonExpired, $credentialsNonExpired, $accountNonLocked);
}
return new InMemoryUser($storedUser->getUsername(), $storedUser->getPassword(), $storedUser->getRoles(), $storedUser->isEnabled());
}
/**
@ -87,7 +102,12 @@ class InMemoryUserProvider implements UserProviderInterface
*/
public function supportsClass(string $class)
{
return 'Symfony\Component\Security\Core\User\User' === $class;
// @deprecated since Symfony 5.3
if (User::class === $class) {
return true;
}
return InMemoryUser::class == $class;
}
/**
@ -95,7 +115,7 @@ class InMemoryUserProvider implements UserProviderInterface
*
* @throws UsernameNotFoundException if user whose given username does not exist
*/
private function getUser(string $username): User
private function getUser(string $username)/*: InMemoryUser */
{
if (!isset($this->users[strtolower($username)])) {
$ex = new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $username));

View File

@ -11,12 +11,16 @@
namespace Symfony\Component\Security\Core\User;
trigger_deprecation('symfony/security-core', '5.3', 'The "%s" class is deprecated, use "%s" instead.', User::class, InMemoryUser::class);
/**
* User is the user implementation used by the in-memory user provider.
*
* This should not be used for anything else.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated since Symfony 5.3, use {@link InMemoryUser} instead
*/
final class User implements UserInterface, PasswordAuthenticatedUserInterface, EquatableInterface
{
@ -171,8 +175,8 @@ final class User implements UserInterface, PasswordAuthenticatedUserInterface, E
return false;
}
$currentRoles = array_map('strval', (array) $this->getRoles());
$newRoles = array_map('strval', (array) $user->getRoles());
$currentRoles = array_map('strval', (array)$this->getRoles());
$newRoles = array_map('strval', (array)$user->getRoles());
$rolesChanged = \count($currentRoles) !== \count($newRoles) || \count($currentRoles) !== \count(array_intersect($currentRoles, $newRoles));
if ($rolesChanged) {
return false;

View File

@ -16,54 +16,19 @@ use Symfony\Component\Security\Core\Exception\CredentialsExpiredException;
use Symfony\Component\Security\Core\Exception\DisabledException;
use Symfony\Component\Security\Core\Exception\LockedException;
/**
trigger_deprecation('symfony/security-core', '5.3', 'The "%s" class is deprecated, use "%s" instead.', UserChecker::class, InMemoryUserChecker::class);
class_exists(InMemoryUserChecker::class);
if (false) {
/**
* UserChecker checks the user account flags.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated since Symfony 5.3, use {@link InMemoryUserChecker} instead
*/
class UserChecker implements UserCheckerInterface
{
/**
* {@inheritdoc}
*/
public function checkPreAuth(UserInterface $user)
class UserChecker
{
if (!$user instanceof User) {
return;
}
if (!$user->isAccountNonLocked()) {
$ex = new LockedException('User account is locked.');
$ex->setUser($user);
throw $ex;
}
if (!$user->isEnabled()) {
$ex = new DisabledException('User account is disabled.');
$ex->setUser($user);
throw $ex;
}
if (!$user->isAccountNonExpired()) {
$ex = new AccountExpiredException('User account has expired.');
$ex->setUser($user);
throw $ex;
}
}
/**
* {@inheritdoc}
*/
public function checkPostAuth(UserInterface $user)
{
if (!$user instanceof User) {
return;
}
if (!$user->isCredentialsNonExpired()) {
$ex = new CredentialsExpiredException('User credentials have expired.');
$ex->setUser($user);
throw $ex;
}
}
}

View File

@ -16,7 +16,7 @@ use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\InMemoryUser;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Guard\Authenticator\GuardBridgeAuthenticator;
use Symfony\Component\Security\Guard\AuthenticatorInterface;
@ -77,7 +77,7 @@ class GuardBridgeAuthenticatorTest extends TestCase
->with($request)
->willReturn($credentials);
$user = new User('test', null, ['ROLE_USER']);
$user = new InMemoryUser('test', null, ['ROLE_USER']);
$this->guardAuthenticator->expects($this->once())
->method('getUser')
->with($credentials, $this->userProvider)
@ -145,7 +145,7 @@ class GuardBridgeAuthenticatorTest extends TestCase
public function testCreateAuthenticatedToken()
{
$user = new User('test', null, ['ROLE_USER']);
$user = new InMemoryUser('test', null, ['ROLE_USER']);
$token = new PostAuthenticationGuardToken($user, 'main', ['ROLE_USER']);
$this->guardAuthenticator->expects($this->once())
@ -159,7 +159,7 @@ class GuardBridgeAuthenticatorTest extends TestCase
public function testHandleSuccess()
{
$request = new Request();
$token = new PostAuthenticationGuardToken(new User('test', null, ['ROLE_USER']), 'main', ['ROLE_USER']);
$token = new PostAuthenticationGuardToken(new InMemoryUser('test', null, ['ROLE_USER']), 'main', ['ROLE_USER']);
$response = new Response();
$this->guardAuthenticator->expects($this->once())

View File

@ -18,7 +18,7 @@ use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\InMemoryUser;
use Symfony\Component\Security\Http\Authentication\AuthenticatorManager;
use Symfony\Component\Security\Http\Authenticator\InteractiveAuthenticatorInterface;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
@ -42,7 +42,7 @@ class AuthenticatorManagerTest extends TestCase
$this->tokenStorage = $this->createMock(TokenStorageInterface::class);
$this->eventDispatcher = new EventDispatcher();
$this->request = new Request();
$this->user = new User('wouter', null);
$this->user = new InMemoryUser('wouter', null);
$this->token = $this->createMock(TokenInterface::class);
$this->response = $this->createMock(Response::class);
}

View File

@ -17,7 +17,7 @@ use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\InMemoryUser;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
@ -38,7 +38,7 @@ class FormLoginAuthenticatorTest extends TestCase
protected function setUp(): void
{
$this->userProvider = $this->createMock(UserProviderInterface::class);
$this->userProvider->expects($this->any())->method('loadUserByUsername')->willReturn(new User('test', 's$cr$t'));
$this->userProvider->expects($this->any())->method('loadUserByUsername')->willReturn(new InMemoryUser('test', 's$cr$t'));
$this->successHandler = $this->createMock(AuthenticationSuccessHandlerInterface::class);
$this->failureHandler = $this->createMock(AuthenticationFailureHandlerInterface::class);
}
@ -150,7 +150,7 @@ class FormLoginAuthenticatorTest extends TestCase
$request->setSession($this->createSession());
$this->userProvider = $this->createMock(PasswordUpgraderProvider::class);
$this->userProvider->expects($this->any())->method('loadUserByUsername')->willReturn(new User('test', 's$cr$t'));
$this->userProvider->expects($this->any())->method('loadUserByUsername')->willReturn(new InMemoryUser('test', 's$cr$t'));
$this->setUpAuthenticator();
$passport = $this->authenticator->authenticate($request);

View File

@ -4,7 +4,7 @@ namespace Symfony\Component\Security\Http\Tests\Authenticator;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\InMemoryUser;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Http\Authenticator\HttpBasicAuthenticator;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\PasswordUpgradeBadge;
@ -44,7 +44,7 @@ class HttpBasicAuthenticatorTest extends TestCase
->expects($this->any())
->method('loadUserByUsername')
->with('TheUsername')
->willReturn($user = new User('TheUsername', 'ThePassword'));
->willReturn($user = new InMemoryUser('TheUsername', 'ThePassword'));
$passport = $this->authenticator->authenticate($request);
$this->assertEquals('ThePassword', $passport->getBadge(PasswordCredentials::class)->getPassword());
@ -78,7 +78,7 @@ class HttpBasicAuthenticatorTest extends TestCase
]);
$this->userProvider = $this->createMock(PasswordUpgraderProvider::class);
$this->userProvider->expects($this->any())->method('loadUserByUsername')->willReturn(new User('test', 's$cr$t'));
$this->userProvider->expects($this->any())->method('loadUserByUsername')->willReturn(new InMemoryUser('test', 's$cr$t'));
$authenticator = new HttpBasicAuthenticator('test', $this->userProvider);
$passport = $authenticator->authenticate($request);

View File

@ -16,7 +16,7 @@ use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authentication\Token\RememberMeToken;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\InMemoryUser;
use Symfony\Component\Security\Http\Authenticator\RememberMeAuthenticator;
use Symfony\Component\Security\Http\RememberMe\RememberMeServicesInterface;
@ -70,7 +70,7 @@ class RememberMeAuthenticatorTest extends TestCase
public function testAuthenticate()
{
$this->request->attributes->set('_remember_me_token', new RememberMeToken($user = new User('wouter', 'test'), 'main', 'secret'));
$this->request->attributes->set('_remember_me_token', new RememberMeToken($user = new InMemoryUser('wouter', 'test'), 'main', 'secret'));
$passport = $this->authenticator->authenticate($this->request);
$this->assertSame($user, $passport->getUser());

View File

@ -14,7 +14,7 @@ namespace Symfony\Component\Security\Http\Tests\Authenticator;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\InMemoryUser;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Http\Authenticator\RemoteUserAuthenticator;
@ -49,7 +49,7 @@ class RemoteUserAuthenticatorTest extends TestCase
$userProvider->expects($this->once())
->method('loadUserByUsername')
->with('TheUsername')
->willReturn($user = new User('TheUsername', null));
->willReturn($user = new InMemoryUser('TheUsername', null));
$passport = $authenticator->authenticate($request);
$this->assertEquals($user, $passport->getUser());

View File

@ -14,7 +14,7 @@ namespace Symfony\Component\Security\Http\Tests\Authenticator;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\InMemoryUser;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Http\Authenticator\X509Authenticator;
@ -48,7 +48,7 @@ class X509AuthenticatorTest extends TestCase
$this->userProvider->expects($this->any())
->method('loadUserByUsername')
->with($username)
->willReturn(new User($username, null));
->willReturn(new InMemoryUser($username, null));
$passport = $this->authenticator->authenticate($request);
$this->assertEquals($username, $passport->getUser()->getUsername());
@ -72,7 +72,7 @@ class X509AuthenticatorTest extends TestCase
$this->userProvider->expects($this->once())
->method('loadUserByUsername')
->with($emailAddress)
->willReturn(new User($emailAddress, null));
->willReturn(new InMemoryUser($emailAddress, null));
$passport = $this->authenticator->authenticate($request);
$this->assertEquals($emailAddress, $passport->getUser()->getUsername());
@ -108,7 +108,7 @@ class X509AuthenticatorTest extends TestCase
$this->userProvider->expects($this->once())
->method('loadUserByUsername')
->with('TheUser')
->willReturn(new User('TheUser', null));
->willReturn(new InMemoryUser('TheUser', null));
$passport = $this->authenticator->authenticate($request);
$this->assertEquals('TheUser', $passport->getUser()->getUsername());
@ -126,7 +126,7 @@ class X509AuthenticatorTest extends TestCase
$this->userProvider->expects($this->once())
->method('loadUserByUsername')
->with('cert@example.com')
->willReturn(new User('cert@example.com', null));
->willReturn(new InMemoryUser('cert@example.com', null));
$passport = $authenticator->authenticate($request);
$this->assertEquals('cert@example.com', $passport->getUser()->getUsername());

View File

@ -12,9 +12,8 @@
namespace Symfony\Component\Security\Http\Tests\EventListener;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\InMemoryUser;
use Symfony\Component\Security\Http\Authenticator\AuthenticatorInterface;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\PasswordUpgradeBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
@ -37,7 +36,7 @@ class CheckCredentialsListenerTest extends TestCase
{
$this->hasherFactory = $this->createMock(PasswordHasherFactoryInterface::class);
$this->listener = new CheckCredentialsListener($this->hasherFactory);
$this->user = new User('wouter', 'password-hash');
$this->user = new InMemoryUser('wouter', 'password-hash');
}
/**

View File

@ -13,7 +13,7 @@ namespace Symfony\Component\Security\Http\Tests\EventListener;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\InMemoryUser;
use Symfony\Component\Security\Csrf\CsrfToken;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
use Symfony\Component\Security\Http\Authenticator\AuthenticatorInterface;
@ -76,7 +76,7 @@ class CsrfProtectionListenerTest extends TestCase
private function createPassport(?CsrfTokenBadge $badge)
{
$passport = new SelfValidatingPassport(new UserBadge('wouter', function ($username) { return new User($username, 'pass'); }));
$passport = new SelfValidatingPassport(new UserBadge('wouter', function ($username) { return new InMemoryUser($username, 'pass'); }));
if ($badge) {
$passport->addBadge($badge);
}

View File

@ -16,7 +16,7 @@ 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\User\User;
use Symfony\Component\Security\Core\User\InMemoryUser;
use Symfony\Component\Security\Http\Authenticator\AuthenticatorInterface;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\RememberMeBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
@ -48,7 +48,7 @@ class RememberMeListenerTest extends TestCase
{
$this->rememberMeServices->expects($this->never())->method('loginSuccess');
$event = $this->createLoginSuccessfulEvent('main_firewall', $this->response, new SelfValidatingPassport(new UserBadge('wouter', function ($username) { return new User($username, null); })));
$event = $this->createLoginSuccessfulEvent('main_firewall', $this->response, new SelfValidatingPassport(new UserBadge('wouter', function ($username) { return new InMemoryUser($username, null); })));
$this->listener->onSuccessfulLogin($event);
}
@ -79,7 +79,7 @@ class RememberMeListenerTest extends TestCase
private function createLoginSuccessfulEvent($firewallName, $response, PassportInterface $passport = null)
{
if (null === $passport) {
$passport = new SelfValidatingPassport(new UserBadge('test', function ($username) { return new User($username, null); }), [new RememberMeBadge()]);
$passport = new SelfValidatingPassport(new UserBadge('test', function ($username) { return new InMemoryUser($username, null); }), [new RememberMeBadge()]);
}
return new LoginSuccessEvent($this->createMock(AuthenticatorInterface::class), $passport, $this->token, $this->request, $response, $firewallName);

View File

@ -15,7 +15,7 @@ use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\InMemoryUser;
use Symfony\Component\Security\Http\Authenticator\AuthenticatorInterface;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;
@ -64,7 +64,7 @@ class SessionStrategyListenerTest extends TestCase
private function createEvent($firewallName)
{
return new LoginSuccessEvent($this->createMock(AuthenticatorInterface::class), new SelfValidatingPassport(new UserBadge('test', function ($username) { return new User($username, null); })), $this->token, $this->request, null, $firewallName);
return new LoginSuccessEvent($this->createMock(AuthenticatorInterface::class), new SelfValidatingPassport(new UserBadge('test', function ($username) { return new InMemoryUser($username, null); })), $this->token, $this->request, null, $firewallName);
}
private function configurePreviousSession()

View File

@ -14,7 +14,7 @@ namespace Symfony\Component\Security\Http\Tests\EventListener;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken;
use Symfony\Component\Security\Core\Event\AuthenticationSuccessEvent;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\InMemoryUser;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Http\Authenticator\AuthenticatorInterface;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\PreAuthenticatedUserBadge;
@ -35,7 +35,7 @@ class UserCheckerListenerTest extends TestCase
{
$this->userChecker = $this->createMock(UserCheckerInterface::class);
$this->listener = new UserCheckerListener($this->userChecker);
$this->user = new User('test', null);
$this->user = new InMemoryUser('test', null);
}
public function testPreAuth()

View File

@ -12,7 +12,7 @@
namespace Symfony\Component\Security\Http\Tests\EventListener;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\InMemoryUser;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Http\Authenticator\AuthenticatorInterface;
@ -41,7 +41,7 @@ class UserProviderListenerTest extends TestCase
$badge = $passport->getBadge(UserBadge::class);
$this->assertEquals([$this->userProvider, 'loadUserByUsername'], $badge->getUserLoader());
$user = new User('wouter', null);
$user = new InMemoryUser('wouter', null);
$this->userProvider->expects($this->once())->method('loadUserByUsername')->with('wouter')->willReturn($user);
$this->assertSame($user, $passport->getUser());
}

View File

@ -25,7 +25,7 @@ use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface
use Symfony\Component\Security\Core\Authorization\Voter\AuthenticatedVoter;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\InMemoryUser;
use Symfony\Component\Security\Http\AccessMapInterface;
use Symfony\Component\Security\Http\Event\LazyResponseEvent;
use Symfony\Component\Security\Http\Firewall\AccessListener;
@ -297,7 +297,7 @@ class AccessListenerTest extends TestCase
public function testHandleWhenPublicAccessWhileAuthenticated()
{
$token = new UsernamePasswordToken(new User('Wouter', null, ['ROLE_USER']), null, 'main', ['ROLE_USER']);
$token = new UsernamePasswordToken(new InMemoryUser('Wouter', null, ['ROLE_USER']), null, 'main', ['ROLE_USER']);
$tokenStorage = new TokenStorage();
$tokenStorage->setToken($token);
$request = new Request();

View File

@ -32,7 +32,7 @@ use Symfony\Component\Security\Core\Authentication\Token\Storage\UsageTrackingTo
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\InMemoryUser;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Http\Event\DeauthenticatedEvent;
@ -247,7 +247,7 @@ class ContextListenerTest extends TestCase
public function testIfTokenIsDeauthenticated()
{
$refreshedUser = new User('foobar', 'baz');
$refreshedUser = new InMemoryUser('foobar', 'baz');
$tokenStorage = $this->handleEventWithPreviousSession([new NotSupportingUserProvider(true), new NotSupportingUserProvider(false), new SupportingUserProvider($refreshedUser)]);
$this->assertNull($tokenStorage->getToken());
@ -256,8 +256,8 @@ class ContextListenerTest extends TestCase
public function testIfTokenIsNotDeauthenticated()
{
$tokenStorage = new TokenStorage();
$badRefreshedUser = new User('foobar', 'baz');
$goodRefreshedUser = new User('foobar', 'bar');
$badRefreshedUser = new InMemoryUser('foobar', 'baz');
$goodRefreshedUser = new InMemoryUser('foobar', 'bar');
$tokenStorage = $this->handleEventWithPreviousSession([new SupportingUserProvider($badRefreshedUser), new SupportingUserProvider($goodRefreshedUser)], $goodRefreshedUser);
$this->assertSame($goodRefreshedUser, $tokenStorage->getToken()->getUser());
}
@ -265,7 +265,7 @@ class ContextListenerTest extends TestCase
public function testRememberMeGetsCanceledIfTokenIsDeauthenticated()
{
$tokenStorage = new TokenStorage();
$refreshedUser = new User('foobar', 'baz');
$refreshedUser = new InMemoryUser('foobar', 'baz');
$rememberMeServices = $this->createMock(RememberMeServicesInterface::class);
$rememberMeServices->expects($this->once())->method('loginFail');
@ -277,7 +277,7 @@ class ContextListenerTest extends TestCase
public function testTryAllUserProvidersUntilASupportingUserProviderIsFound()
{
$refreshedUser = new User('foobar', 'baz');
$refreshedUser = new InMemoryUser('foobar', 'baz');
$tokenStorage = $this->handleEventWithPreviousSession([new NotSupportingUserProvider(true), new NotSupportingUserProvider(false), new SupportingUserProvider($refreshedUser)], $refreshedUser);
$this->assertSame($refreshedUser, $tokenStorage->getToken()->getUser());
@ -285,7 +285,7 @@ class ContextListenerTest extends TestCase
public function testNextSupportingUserProviderIsTriedIfPreviousSupportingUserProviderDidNotLoadTheUser()
{
$refreshedUser = new User('foobar', 'baz');
$refreshedUser = new InMemoryUser('foobar', 'baz');
$tokenStorage = $this->handleEventWithPreviousSession([new NotSupportingUserProvider(true), new NotSupportingUserProvider(false), new SupportingUserProvider($refreshedUser)], $refreshedUser);
$this->assertSame($refreshedUser, $tokenStorage->getToken()->getUser());
@ -306,7 +306,7 @@ class ContextListenerTest extends TestCase
public function testAcceptsProvidersAsTraversable()
{
$refreshedUser = new User('foobar', 'baz');
$refreshedUser = new InMemoryUser('foobar', 'baz');
$tokenStorage = $this->handleEventWithPreviousSession(new \ArrayObject([new NotSupportingUserProvider(true), new NotSupportingUserProvider(false), new SupportingUserProvider($refreshedUser)]), $refreshedUser);
$this->assertSame($refreshedUser, $tokenStorage->getToken()->getUser());
@ -315,9 +315,9 @@ class ContextListenerTest extends TestCase
public function testDeauthenticatedEvent()
{
$tokenStorage = new TokenStorage();
$refreshedUser = new User('foobar', 'baz');
$refreshedUser = new InMemoryUser('foobar', 'baz');
$user = new User('foo', 'bar');
$user = new InMemoryUser('foo', 'bar');
$session = new Session(new MockArraySessionStorage());
$session->set('_security_context_key', serialize(new UsernamePasswordToken($user, '', 'context_key', ['ROLE_USER'])));
@ -420,7 +420,7 @@ class ContextListenerTest extends TestCase
private function handleEventWithPreviousSession($userProviders, UserInterface $user = null, RememberMeServicesInterface $rememberMeServices = null)
{
$tokenUser = $user ?: new User('foo', 'bar');
$tokenUser = $user ?: new InMemoryUser('foo', 'bar');
$session = new Session(new MockArraySessionStorage());
$session->set('_security_context_key', serialize(new UsernamePasswordToken($tokenUser, '', 'context_key', ['ROLE_USER'])));
@ -500,7 +500,7 @@ class SupportingUserProvider implements UserProviderInterface
{
private $refreshedUser;
public function __construct(User $refreshedUser = null)
public function __construct(InMemoryUser $refreshedUser = null)
{
$this->refreshedUser = $refreshedUser;
}
@ -511,7 +511,7 @@ class SupportingUserProvider implements UserProviderInterface
public function refreshUser(UserInterface $user): UserInterface
{
if (!$user instanceof User) {
if (!$user instanceof InMemoryUser) {
throw new UnsupportedUserException();
}
@ -524,6 +524,6 @@ class SupportingUserProvider implements UserProviderInterface
public function supportsClass($class): bool
{
return 'Symfony\Component\Security\Core\User\User' === $class;
return InMemoryUser::class === $class;
}
}

View File

@ -23,7 +23,7 @@ use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\InMemoryUser;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
@ -165,7 +165,7 @@ class SwitchUserListenerTest extends TestCase
{
$this->expectException(AccessDeniedException::class);
$token = new UsernamePasswordToken('username', '', 'key', ['ROLE_FOO']);
$user = new User('username', 'password', []);
$user = new InMemoryUser('username', 'password', []);
$this->tokenStorage->setToken($token);
$this->request->query->set('_switch_user', 'kuba');
@ -206,7 +206,7 @@ class SwitchUserListenerTest extends TestCase
public function testSwitchUser()
{
$token = new UsernamePasswordToken('username', '', 'key', ['ROLE_FOO']);
$user = new User('username', 'password', []);
$user = new InMemoryUser('username', 'password', []);
$this->tokenStorage->setToken($token);
$this->request->query->set('_switch_user', 'kuba');
@ -238,7 +238,7 @@ class SwitchUserListenerTest extends TestCase
$tokenStorage = new TokenStorage();
$tokenStorage->setToken($alreadySwitchedToken);
$targetUser = new User('kuba', 'password', ['ROLE_FOO', 'ROLE_BAR']);
$targetUser = new InMemoryUser('kuba', 'password', ['ROLE_FOO', 'ROLE_BAR']);
$this->request->query->set('_switch_user', 'kuba');
@ -266,7 +266,7 @@ class SwitchUserListenerTest extends TestCase
public function testSwitchUserWorksWithFalsyUsernames()
{
$token = new UsernamePasswordToken('username', '', 'key', ['ROLE_FOO']);
$user = new User('username', 'password', []);
$user = new InMemoryUser('username', 'password', []);
$this->tokenStorage->setToken($token);
$this->request->query->set('_switch_user', '0');
@ -293,7 +293,7 @@ class SwitchUserListenerTest extends TestCase
public function testSwitchUserKeepsOtherQueryStringParameters()
{
$token = new UsernamePasswordToken('username', '', 'key', ['ROLE_FOO']);
$user = new User('username', 'password', []);
$user = new InMemoryUser('username', 'password', []);
$this->tokenStorage->setToken($token);
$this->request->query->replace([
@ -322,10 +322,10 @@ class SwitchUserListenerTest extends TestCase
public function testSwitchUserWithReplacedToken()
{
$user = new User('username', 'password', []);
$user = new InMemoryUser('username', 'password', []);
$token = new UsernamePasswordToken($user, '', 'provider123', ['ROLE_FOO']);
$user = new User('replaced', 'password', []);
$user = new InMemoryUser('replaced', 'password', []);
$replacedToken = new UsernamePasswordToken($user, '', 'provider123', ['ROLE_BAR']);
$this->tokenStorage->setToken($token);
@ -374,7 +374,7 @@ class SwitchUserListenerTest extends TestCase
public function testSwitchUserStateless()
{
$token = new UsernamePasswordToken('username', '', 'key', ['ROLE_FOO']);
$user = new User('username', 'password', []);
$user = new InMemoryUser('username', 'password', []);
$this->tokenStorage->setToken($token);
$this->request->query->set('_switch_user', 'kuba');