login consent app sql

This commit is contained in:
2022-05-03 08:54:45 +02:00
parent e7253acfd8
commit f9a6535906
1652 changed files with 187600 additions and 45 deletions

View File

@ -0,0 +1,35 @@
<?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\Authentication;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
/**
* AuthenticationManagerInterface is the interface for authentication managers,
* which process Token authentication.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @internal since Symfony 5.3
*/
interface AuthenticationManagerInterface
{
/**
* Attempts to authenticate a TokenInterface object.
*
* @return TokenInterface
*
* @throws AuthenticationException if the authentication fails
*/
public function authenticate(TokenInterface $token);
}

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\Authentication;
use Symfony\Component\PasswordHasher\Exception\InvalidPasswordException;
use Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\AuthenticationEvents;
use Symfony\Component\Security\Core\Event\AuthenticationFailureEvent;
use Symfony\Component\Security\Core\Event\AuthenticationSuccessEvent;
use Symfony\Component\Security\Core\Exception\AccountStatusException;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\Exception\ProviderNotFoundException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
trigger_deprecation('symfony/security-core', '5.3', 'The "%s" class is deprecated, use the new authenticator system instead.', AuthenticationProviderManager::class);
// Help opcache.preload discover always-needed symbols
class_exists(AuthenticationEvents::class);
class_exists(AuthenticationFailureEvent::class);
class_exists(AuthenticationSuccessEvent::class);
/**
* AuthenticationProviderManager uses a list of AuthenticationProviderInterface
* instances to authenticate a Token.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*
* @deprecated since Symfony 5.3, use the new authenticator system instead
*/
class AuthenticationProviderManager implements AuthenticationManagerInterface
{
private $providers;
private $eraseCredentials;
private $eventDispatcher;
/**
* @param iterable<mixed, AuthenticationProviderInterface> $providers An iterable with AuthenticationProviderInterface instances as values
* @param bool $eraseCredentials Whether to erase credentials after authentication or not
*
* @throws \InvalidArgumentException
*/
public function __construct(iterable $providers, bool $eraseCredentials = true)
{
if (!$providers) {
throw new \InvalidArgumentException('You must at least add one authentication provider.');
}
$this->providers = $providers;
$this->eraseCredentials = $eraseCredentials;
}
public function setEventDispatcher(EventDispatcherInterface $dispatcher)
{
$this->eventDispatcher = $dispatcher;
}
/**
* {@inheritdoc}
*/
public function authenticate(TokenInterface $token)
{
$lastException = null;
$result = null;
foreach ($this->providers as $provider) {
if (!$provider instanceof AuthenticationProviderInterface) {
throw new \InvalidArgumentException(sprintf('Provider "%s" must implement the AuthenticationProviderInterface.', get_debug_type($provider)));
}
if (!$provider->supports($token)) {
continue;
}
try {
$result = $provider->authenticate($token);
if (null !== $result) {
break;
}
} catch (AccountStatusException $e) {
$lastException = $e;
break;
} catch (AuthenticationException $e) {
$lastException = $e;
} catch (InvalidPasswordException $e) {
$lastException = new BadCredentialsException('Bad credentials.', 0, $e);
}
}
if (null !== $result) {
if (true === $this->eraseCredentials) {
$result->eraseCredentials();
}
if (null !== $this->eventDispatcher) {
$this->eventDispatcher->dispatch(new AuthenticationSuccessEvent($result), AuthenticationEvents::AUTHENTICATION_SUCCESS);
}
// @deprecated since Symfony 5.3
if ($result->getUser() instanceof UserInterface && !method_exists($result->getUser(), 'getUserIdentifier')) {
trigger_deprecation('symfony/security-core', '5.3', 'Not implementing method "getUserIdentifier(): string" in user class "%s" is deprecated. This method will replace "getUsername()" in Symfony 6.0.', get_debug_type($result->getUser()));
}
return $result;
}
if (null === $lastException) {
$lastException = new ProviderNotFoundException(sprintf('No Authentication Provider found for token of class "%s".', \get_class($token)));
}
if (null !== $this->eventDispatcher) {
$this->eventDispatcher->dispatch(new AuthenticationFailureEvent($token, $lastException), AuthenticationEvents::AUTHENTICATION_FAILURE);
}
$lastException->setToken($token);
throw $lastException;
}
}

View File

@ -0,0 +1,59 @@
<?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\Authentication;
use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
use Symfony\Component\Security\Core\Authentication\Token\RememberMeToken;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
/**
* The default implementation of the authentication trust resolver.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
class AuthenticationTrustResolver implements AuthenticationTrustResolverInterface
{
public function isAuthenticated(TokenInterface $token = null): bool
{
return $token && $token->getUser()
// @deprecated since Symfony 5.4, TokenInterface::isAuthenticated() and AnonymousToken no longer exists in 6.0
&& !$token instanceof AnonymousToken && (!method_exists($token, 'isAuthenticated') || $token->isAuthenticated(false));
}
/**
* {@inheritdoc}
*/
public function isAnonymous(TokenInterface $token = null/*, $deprecation = true*/)
{
if (1 === \func_num_args() || false !== func_get_arg(1)) {
trigger_deprecation('symfony/security-core', '5.4', 'The "%s()" method is deprecated, use "isAuthenticated()" or "isFullFledged()" if you want to check if the request is (fully) authenticated.', __METHOD__);
}
return $token instanceof AnonymousToken || ($token && !$token->getUser());
}
/**
* {@inheritdoc}
*/
public function isRememberMe(TokenInterface $token = null)
{
return $token && $token instanceof RememberMeToken;
}
/**
* {@inheritdoc}
*/
public function isFullFledged(TokenInterface $token = null)
{
return $token && !$this->isAnonymous($token, false) && !$this->isRememberMe($token);
}
}

View File

@ -0,0 +1,51 @@
<?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\Authentication;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
/**
* Interface for resolving the authentication status of a given token.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*
* @method bool isAuthenticated(TokenInterface $token = null)
*/
interface AuthenticationTrustResolverInterface
{
/**
* Resolves whether the passed token implementation is authenticated
* anonymously.
*
* If null is passed, the method must return false.
*
* @return bool
*
* @deprecated since Symfony 5.4, use !isAuthenticated() instead
*/
public function isAnonymous(TokenInterface $token = null);
/**
* Resolves whether the passed token implementation is authenticated
* using remember-me capabilities.
*
* @return bool
*/
public function isRememberMe(TokenInterface $token = null);
/**
* Resolves whether the passed token implementation is fully authenticated.
*
* @return bool
*/
public function isFullFledged(TokenInterface $token = null);
}

View File

@ -0,0 +1,69 @@
<?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\Authentication\Provider;
use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
trigger_deprecation('symfony/security-core', '5.3', 'The "%s" class is deprecated, use the new authenticator system instead.', AnonymousAuthenticationProvider::class);
/**
* AnonymousAuthenticationProvider validates AnonymousToken instances.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated since Symfony 5.3, use the new authenticator system instead
*/
class AnonymousAuthenticationProvider implements AuthenticationProviderInterface
{
/**
* Used to determine if the token is created by the application
* instead of a malicious client.
*
* @var string
*/
private $secret;
/**
* @param string $secret The secret shared with the AnonymousToken
*/
public function __construct(string $secret)
{
$this->secret = $secret;
}
/**
* {@inheritdoc}
*/
public function authenticate(TokenInterface $token)
{
if (!$this->supports($token)) {
throw new AuthenticationException('The token is not supported by this authentication provider.');
}
if ($this->secret !== $token->getSecret()) {
throw new BadCredentialsException('The Token does not contain the expected key.');
}
return $token;
}
/**
* {@inheritdoc}
*/
public function supports(TokenInterface $token)
{
return $token instanceof AnonymousToken;
}
}

View File

@ -0,0 +1,44 @@
<?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\Authentication\Provider;
use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
trigger_deprecation('symfony/security-core', '5.3', 'The "%s" interface is deprecated, use the new authenticator system instead.', AuthenticationProviderInterface::class);
/**
* AuthenticationProviderInterface is the interface for all authentication
* providers.
*
* Concrete implementations processes specific Token instances.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated since Symfony 5.3, use the new authenticator system instead
*/
interface AuthenticationProviderInterface extends AuthenticationManagerInterface
{
/**
* Use this constant for not provided username.
*
* @var string
*/
public const USERNAME_NONE_PROVIDED = 'NONE_PROVIDED';
/**
* Checks whether this provider supports the given token.
*
* @return bool
*/
public function supports(TokenInterface $token);
}

View File

@ -0,0 +1,146 @@
<?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\Authentication\Provider;
use Symfony\Component\PasswordHasher\Hasher\PasswordHasherFactoryInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
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\UserNotFoundException;
use Symfony\Component\Security\Core\User\LegacyPasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\PasswordUpgraderInterface;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
trigger_deprecation('symfony/security-core', '5.3', 'The "%s" class is deprecated, use the new authenticator system instead.', DaoAuthenticationProvider::class);
/**
* DaoAuthenticationProvider uses a UserProviderInterface to retrieve the user
* for a UsernamePasswordToken.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated since Symfony 5.3, use the new authenticator system instead
*/
class DaoAuthenticationProvider extends UserAuthenticationProvider
{
private $hasherFactory;
private $userProvider;
/**
* @param PasswordHasherFactoryInterface $hasherFactory
*/
public function __construct(UserProviderInterface $userProvider, UserCheckerInterface $userChecker, string $providerKey, $hasherFactory, bool $hideUserNotFoundExceptions = true)
{
parent::__construct($userChecker, $providerKey, $hideUserNotFoundExceptions);
if ($hasherFactory instanceof EncoderFactoryInterface) {
trigger_deprecation('symfony/security-core', '5.3', 'Passing a "%s" instance to the "%s" constructor is deprecated, use "%s" instead.', EncoderFactoryInterface::class, __CLASS__, PasswordHasherFactoryInterface::class);
}
$this->hasherFactory = $hasherFactory;
$this->userProvider = $userProvider;
}
/**
* {@inheritdoc}
*/
protected function checkAuthentication(UserInterface $user, UsernamePasswordToken $token)
{
$currentUser = $token->getUser();
if ($currentUser instanceof UserInterface) {
if ($currentUser->getPassword() !== $user->getPassword()) {
throw new BadCredentialsException('The credentials were changed from another session.');
}
} else {
if ('' === ($presentedPassword = $token->getCredentials())) {
throw new BadCredentialsException('The presented password cannot be empty.');
}
if (null === $user->getPassword()) {
throw new BadCredentialsException('The presented password is invalid.');
}
if (!$user instanceof PasswordAuthenticatedUserInterface) {
trigger_deprecation('symfony/security-core', '5.3', 'Using password-based authentication listeners while not implementing "%s" interface from class "%s" is deprecated.', PasswordAuthenticatedUserInterface::class, get_debug_type($user));
}
$salt = $user->getSalt();
if ($salt && !$user instanceof LegacyPasswordAuthenticatedUserInterface) {
trigger_deprecation('symfony/security-core', '5.3', 'Returning a string from "getSalt()" without implementing the "%s" interface is deprecated, the "%s" class should implement it.', LegacyPasswordAuthenticatedUserInterface::class, get_debug_type($user));
}
// deprecated since Symfony 5.3
if ($this->hasherFactory instanceof EncoderFactoryInterface) {
$encoder = $this->hasherFactory->getEncoder($user);
if (!$encoder->isPasswordValid($user->getPassword(), $presentedPassword, $salt)) {
throw new BadCredentialsException('The presented password is invalid.');
}
if ($this->userProvider instanceof PasswordUpgraderInterface && method_exists($encoder, 'needsRehash') && $encoder->needsRehash($user->getPassword())) {
$this->userProvider->upgradePassword($user, $encoder->encodePassword($presentedPassword, $user->getSalt()));
}
return;
}
$hasher = $this->hasherFactory->getPasswordHasher($user);
if (!$hasher->verify($user->getPassword(), $presentedPassword, $salt)) {
throw new BadCredentialsException('The presented password is invalid.');
}
if ($this->userProvider instanceof PasswordUpgraderInterface && $hasher->needsRehash($user->getPassword())) {
$this->userProvider->upgradePassword($user, $hasher->hash($presentedPassword, $salt));
}
}
}
/**
* {@inheritdoc}
*/
protected function retrieveUser(string $userIdentifier, UsernamePasswordToken $token)
{
$user = $token->getUser();
if ($user instanceof UserInterface) {
return $user;
}
try {
// @deprecated since Symfony 5.3, change to $this->userProvider->loadUserByIdentifier() in 6.0
if (method_exists($this->userProvider, 'loadUserByIdentifier')) {
$user = $this->userProvider->loadUserByIdentifier($userIdentifier);
} else {
trigger_deprecation('symfony/security-core', '5.3', 'Not implementing method "loadUserByIdentifier()" in user provider "%s" is deprecated. This method will replace "loadUserByUsername()" in Symfony 6.0.', get_debug_type($this->userProvider));
$user = $this->userProvider->loadUserByUsername($userIdentifier);
}
if (!$user instanceof UserInterface) {
throw new AuthenticationServiceException('The user provider must return a UserInterface object.');
}
return $user;
} catch (UserNotFoundException $e) {
$e->setUserIdentifier($userIdentifier);
throw $e;
} catch (\Exception $e) {
$e = new AuthenticationServiceException($e->getMessage(), 0, $e);
$e->setToken($token);
throw $e;
}
}
}

View File

@ -0,0 +1,121 @@
<?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\Authentication\Provider;
use Symfony\Component\Ldap\Exception\ConnectionException;
use Symfony\Component\Ldap\LdapInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\Exception\LogicException;
use Symfony\Component\Security\Core\Exception\UserNotFoundException;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
trigger_deprecation('symfony/security-core', '5.3', 'The "%s" class is deprecated, use the new authenticator system instead.', LdapBindAuthenticationProvider::class);
/**
* LdapBindAuthenticationProvider authenticates a user against an LDAP server.
*
* The only way to check user credentials is to try to connect the user with its
* credentials to the ldap.
*
* @author Charles Sarrazin <charles@sarraz.in>
*
* @deprecated since Symfony 5.3, use the new authenticator system instead
*/
class LdapBindAuthenticationProvider extends UserAuthenticationProvider
{
private $userProvider;
private $ldap;
private $dnString;
private $queryString;
private $searchDn;
private $searchPassword;
public function __construct(UserProviderInterface $userProvider, UserCheckerInterface $userChecker, string $providerKey, LdapInterface $ldap, string $dnString = '{user_identifier}', bool $hideUserNotFoundExceptions = true, string $searchDn = '', string $searchPassword = '')
{
parent::__construct($userChecker, $providerKey, $hideUserNotFoundExceptions);
$this->userProvider = $userProvider;
$this->ldap = $ldap;
$this->dnString = $dnString;
$this->searchDn = $searchDn;
$this->searchPassword = $searchPassword;
}
/**
* Set a query string to use in order to find a DN for the user identifier.
*/
public function setQueryString(string $queryString)
{
$this->queryString = $queryString;
}
/**
* {@inheritdoc}
*/
protected function retrieveUser(string $userIdentifier, UsernamePasswordToken $token)
{
if (AuthenticationProviderInterface::USERNAME_NONE_PROVIDED === $userIdentifier) {
throw new UserNotFoundException('User identifier cannot be null.');
}
// @deprecated since Symfony 5.3, change to $this->userProvider->loadUserByIdentifier() in 6.0
if (method_exists($this->userProvider, 'loadUserByIdentifier')) {
return $this->userProvider->loadUserByIdentifier($userIdentifier);
} else {
trigger_deprecation('symfony/security-core', '5.3', 'Not implementing method "loadUserByIdentifier()" in user provider "%s" is deprecated. This method will replace "loadUserByUsername()" in Symfony 6.0.', get_debug_type($this->userProvider));
return $this->userProvider->loadUserByUsername($userIdentifier);
}
}
/**
* {@inheritdoc}
*/
protected function checkAuthentication(UserInterface $user, UsernamePasswordToken $token)
{
// @deprecated since Symfony 5.3, change to $token->getUserIdentifier() in 6.0
$userIdentifier = method_exists($token, 'getUserIdentifier') ? $token->getUserIdentifier() : $token->getUsername();
$password = $token->getCredentials();
if ('' === (string) $password) {
throw new BadCredentialsException('The presented password must not be empty.');
}
try {
if ($this->queryString) {
if ('' !== $this->searchDn && '' !== $this->searchPassword) {
$this->ldap->bind($this->searchDn, $this->searchPassword);
} else {
throw new LogicException('Using the "query_string" config without using a "search_dn" and a "search_password" is not supported.');
}
$userIdentifier = $this->ldap->escape($userIdentifier, '', LdapInterface::ESCAPE_FILTER);
$query = str_replace(['{username}', '{user_identifier}'], $userIdentifier, $this->queryString);
$result = $this->ldap->query($this->dnString, $query)->execute();
if (1 !== $result->count()) {
throw new BadCredentialsException('The presented username is invalid.');
}
$dn = $result[0]->getDn();
} else {
$userIdentifier = $this->ldap->escape($userIdentifier, '', LdapInterface::ESCAPE_DN);
$dn = str_replace(['{username}', '{user_identifier}'], $userIdentifier, $this->dnString);
}
$this->ldap->bind($dn, $password);
} catch (ConnectionException $e) {
throw new BadCredentialsException('The presented password is invalid.');
}
}
}

View File

@ -0,0 +1,86 @@
<?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\Authentication\Provider;
use Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken;
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\UserCheckerInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
trigger_deprecation('symfony/security-core', '5.3', 'The "%s" class is deprecated, use the new authenticator system instead.', PreAuthenticatedAuthenticationProvider::class);
/**
* Processes a pre-authenticated authentication request.
*
* This authentication provider will not perform any checks on authentication
* requests, as they should already be pre-authenticated. However, the
* UserProviderInterface implementation may still throw a
* UserNotFoundException, for example.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated since Symfony 5.3, use the new authenticator system instead
*/
class PreAuthenticatedAuthenticationProvider implements AuthenticationProviderInterface
{
private $userProvider;
private $userChecker;
private $providerKey;
public function __construct(UserProviderInterface $userProvider, UserCheckerInterface $userChecker, string $providerKey)
{
$this->userProvider = $userProvider;
$this->userChecker = $userChecker;
$this->providerKey = $providerKey;
}
/**
* {@inheritdoc}
*/
public function authenticate(TokenInterface $token)
{
if (!$this->supports($token)) {
throw new AuthenticationException('The token is not supported by this authentication provider.');
}
if (!$user = $token->getUser()) {
throw new BadCredentialsException('No pre-authenticated principal found in request.');
}
$userIdentifier = method_exists($token, 'getUserIdentifier') ? $token->getUserIdentifier() : $token->getUsername();
// @deprecated since Symfony 5.3, change to $this->userProvider->loadUserByIdentifier() in 6.0
if (method_exists($this->userProvider, 'loadUserByIdentifier')) {
$user = $this->userProvider->loadUserByIdentifier($userIdentifier);
} else {
trigger_deprecation('symfony/security-core', '5.3', 'Not implementing method "loadUserByIdentifier()" in user provider "%s" is deprecated. This method will replace "loadUserByUsername()" in Symfony 6.0.', get_debug_type($this->userProvider));
$user = $this->userProvider->loadUserByUsername($userIdentifier);
}
$this->userChecker->checkPostAuth($user);
$authenticatedToken = new PreAuthenticatedToken($user, $token->getCredentials(), $this->providerKey, $user->getRoles());
$authenticatedToken->setAttributes($token->getAttributes());
return $authenticatedToken;
}
/**
* {@inheritdoc}
*/
public function supports(TokenInterface $token)
{
return $token instanceof PreAuthenticatedToken && $this->providerKey === $token->getFirewallName();
}
}

View File

@ -0,0 +1,79 @@
<?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\Authentication\Provider;
use Symfony\Component\Security\Core\Authentication\Token\RememberMeToken;
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\Exception\LogicException;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Core\User\UserInterface;
trigger_deprecation('symfony/security-core', '5.3', 'The "%s" class is deprecated, use the new authenticator system instead.', RememberMeAuthenticationProvider::class);
/**
* @deprecated since Symfony 5.3, use the new authenticator system instead
*/
class RememberMeAuthenticationProvider implements AuthenticationProviderInterface
{
private $userChecker;
private $secret;
private $providerKey;
/**
* @param string $secret A secret
* @param string $providerKey A provider secret
*/
public function __construct(UserCheckerInterface $userChecker, string $secret, string $providerKey)
{
$this->userChecker = $userChecker;
$this->secret = $secret;
$this->providerKey = $providerKey;
}
/**
* {@inheritdoc}
*/
public function authenticate(TokenInterface $token)
{
if (!$this->supports($token)) {
throw new AuthenticationException('The token is not supported by this authentication provider.');
}
if ($this->secret !== $token->getSecret()) {
throw new BadCredentialsException('The presented secret does not match.');
}
$user = $token->getUser();
if (!$user instanceof UserInterface) {
throw new LogicException(sprintf('Method "%s::getUser()" must return a "%s" instance, "%s" returned.', get_debug_type($token), UserInterface::class, get_debug_type($user)));
}
$this->userChecker->checkPreAuth($user);
$this->userChecker->checkPostAuth($user);
$authenticatedToken = new RememberMeToken($user, $this->providerKey, $this->secret);
$authenticatedToken->setAttributes($token->getAttributes());
return $authenticatedToken;
}
/**
* {@inheritdoc}
*/
public function supports(TokenInterface $token)
{
return $token instanceof RememberMeToken && $token->getFirewallName() === $this->providerKey;
}
}

View File

@ -0,0 +1,131 @@
<?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\Authentication\Provider;
use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Exception\AccountStatusException;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\AuthenticationServiceException;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAccountStatusException;
use Symfony\Component\Security\Core\Exception\UserNotFoundException;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Core\User\UserInterface;
trigger_deprecation('symfony/security-core', '5.3', 'The "%s" class is deprecated, use the new authenticator system instead.', UserAuthenticationProvider::class);
/**
* UserProviderInterface retrieves users for UsernamePasswordToken tokens.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated since Symfony 5.3, use the new authenticator system instead
*/
abstract class UserAuthenticationProvider implements AuthenticationProviderInterface
{
private $hideUserNotFoundExceptions;
private $userChecker;
private $providerKey;
/**
* @throws \InvalidArgumentException
*/
public function __construct(UserCheckerInterface $userChecker, string $providerKey, bool $hideUserNotFoundExceptions = true)
{
if (empty($providerKey)) {
throw new \InvalidArgumentException('$providerKey must not be empty.');
}
$this->userChecker = $userChecker;
$this->providerKey = $providerKey;
$this->hideUserNotFoundExceptions = $hideUserNotFoundExceptions;
}
/**
* {@inheritdoc}
*/
public function authenticate(TokenInterface $token)
{
if (!$this->supports($token)) {
throw new AuthenticationException('The token is not supported by this authentication provider.');
}
$username = method_exists($token, 'getUserIdentifier') ? $token->getUserIdentifier() : $token->getUsername();
if ('' === $username || null === $username) {
$username = AuthenticationProviderInterface::USERNAME_NONE_PROVIDED;
}
try {
$user = $this->retrieveUser($username, $token);
} catch (UserNotFoundException $e) {
if ($this->hideUserNotFoundExceptions) {
throw new BadCredentialsException('Bad credentials.', 0, $e);
}
$e->setUserIdentifier($username);
throw $e;
}
if (!$user instanceof UserInterface) {
throw new AuthenticationServiceException('retrieveUser() must return a UserInterface.');
}
try {
$this->userChecker->checkPreAuth($user);
$this->checkAuthentication($user, $token);
$this->userChecker->checkPostAuth($user);
} catch (AccountStatusException|BadCredentialsException $e) {
if ($this->hideUserNotFoundExceptions && !$e instanceof CustomUserMessageAccountStatusException) {
throw new BadCredentialsException('Bad credentials.', 0, $e);
}
throw $e;
}
if ($token instanceof SwitchUserToken) {
$authenticatedToken = new SwitchUserToken($user, $token->getCredentials(), $this->providerKey, $user->getRoles(), $token->getOriginalToken());
} else {
$authenticatedToken = new UsernamePasswordToken($user, $token->getCredentials(), $this->providerKey, $user->getRoles());
}
$authenticatedToken->setAttributes($token->getAttributes());
return $authenticatedToken;
}
/**
* {@inheritdoc}
*/
public function supports(TokenInterface $token)
{
return $token instanceof UsernamePasswordToken && $this->providerKey === $token->getFirewallName();
}
/**
* Retrieves the user from an implementation-specific location.
*
* @return UserInterface
*
* @throws AuthenticationException if the credentials could not be validated
*/
abstract protected function retrieveUser(string $username, UsernamePasswordToken $token);
/**
* Does additional checks on the user and token (like validating the
* credentials).
*
* @throws AuthenticationException if the credentials could not be validated
*/
abstract protected function checkAuthentication(UserInterface $user, UsernamePasswordToken $token);
}

View File

@ -0,0 +1,75 @@
<?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\Authentication\RememberMe;
use Psr\Cache\CacheItemPoolInterface;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class CacheTokenVerifier implements TokenVerifierInterface
{
private $cache;
private $outdatedTokenTtl;
private $cacheKeyPrefix;
/**
* @param int $outdatedTokenTtl How long the outdated token should still be considered valid. Defaults
* to 60, which matches how often the PersistentRememberMeHandler will at
* most refresh tokens. Increasing to more than that is not recommended,
* but you may use a lower value.
*/
public function __construct(CacheItemPoolInterface $cache, int $outdatedTokenTtl = 60, string $cacheKeyPrefix = 'rememberme-stale-')
{
$this->cache = $cache;
$this->outdatedTokenTtl = $outdatedTokenTtl;
$this->cacheKeyPrefix = $cacheKeyPrefix;
}
/**
* {@inheritdoc}
*/
public function verifyToken(PersistentTokenInterface $token, string $tokenValue): bool
{
if (hash_equals($token->getTokenValue(), $tokenValue)) {
return true;
}
$cacheKey = $this->getCacheKey($token);
$item = $this->cache->getItem($cacheKey);
if (!$item->isHit()) {
return false;
}
$outdatedToken = $item->get();
return hash_equals($outdatedToken, $tokenValue);
}
/**
* {@inheritdoc}
*/
public function updateExistingToken(PersistentTokenInterface $token, string $tokenValue, \DateTimeInterface $lastUsed): void
{
// When a token gets updated, persist the outdated token for $outdatedTokenTtl seconds so we can
// still accept it as valid in verifyToken
$item = $this->cache->getItem($this->getCacheKey($token));
$item->set($token->getTokenValue());
$item->expiresAfter($this->outdatedTokenTtl);
$this->cache->save($item);
}
private function getCacheKey(PersistentTokenInterface $token): string
{
return $this->cacheKeyPrefix.rawurlencode($token->getSeries());
}
}

View File

@ -0,0 +1,71 @@
<?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\Authentication\RememberMe;
use Symfony\Component\Security\Core\Exception\TokenNotFoundException;
/**
* This class is used for testing purposes, and is not really suited for production.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
class InMemoryTokenProvider implements TokenProviderInterface
{
private $tokens = [];
/**
* {@inheritdoc}
*/
public function loadTokenBySeries(string $series)
{
if (!isset($this->tokens[$series])) {
throw new TokenNotFoundException('No token found.');
}
return $this->tokens[$series];
}
/**
* {@inheritdoc}
*/
public function updateToken(string $series, string $tokenValue, \DateTime $lastUsed)
{
if (!isset($this->tokens[$series])) {
throw new TokenNotFoundException('No token found.');
}
$token = new PersistentToken(
$this->tokens[$series]->getClass(),
method_exists($this->tokens[$series], 'getUserIdentifier') ? $this->tokens[$series]->getUserIdentifier() : $this->tokens[$series]->getUsername(),
$series,
$tokenValue,
$lastUsed
);
$this->tokens[$series] = $token;
}
/**
* {@inheritdoc}
*/
public function deleteTokenBySeries(string $series)
{
unset($this->tokens[$series]);
}
/**
* {@inheritdoc}
*/
public function createNewToken(PersistentTokenInterface $token)
{
$this->tokens[$token->getSeries()] = $token;
}
}

View File

@ -0,0 +1,95 @@
<?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\Authentication\RememberMe;
/**
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*
* @internal
*/
final class PersistentToken implements PersistentTokenInterface
{
private $class;
private $userIdentifier;
private $series;
private $tokenValue;
private $lastUsed;
public function __construct(string $class, string $userIdentifier, string $series, string $tokenValue, \DateTime $lastUsed)
{
if (empty($class)) {
throw new \InvalidArgumentException('$class must not be empty.');
}
if ('' === $userIdentifier) {
throw new \InvalidArgumentException('$userIdentifier must not be empty.');
}
if (empty($series)) {
throw new \InvalidArgumentException('$series must not be empty.');
}
if (empty($tokenValue)) {
throw new \InvalidArgumentException('$tokenValue must not be empty.');
}
$this->class = $class;
$this->userIdentifier = $userIdentifier;
$this->series = $series;
$this->tokenValue = $tokenValue;
$this->lastUsed = $lastUsed;
}
/**
* {@inheritdoc}
*/
public function getClass(): string
{
return $this->class;
}
/**
* {@inheritdoc}
*/
public function getUsername(): string
{
trigger_deprecation('symfony/security-core', '5.3', 'Method "%s()" is deprecated, use getUserIdentifier() instead.', __METHOD__);
return $this->userIdentifier;
}
public function getUserIdentifier(): string
{
return $this->userIdentifier;
}
/**
* {@inheritdoc}
*/
public function getSeries(): string
{
return $this->series;
}
/**
* {@inheritdoc}
*/
public function getTokenValue(): string
{
return $this->tokenValue;
}
/**
* {@inheritdoc}
*/
public function getLastUsed(): \DateTime
{
return $this->lastUsed;
}
}

View File

@ -0,0 +1,58 @@
<?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\Authentication\RememberMe;
/**
* Interface to be implemented by persistent token classes (such as
* Doctrine entities representing a remember-me token).
*
* @method string getUserIdentifier() returns the identifier used to authenticate (e.g. their email address or username)
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
interface PersistentTokenInterface
{
/**
* Returns the class of the user.
*
* @return string
*/
public function getClass();
/**
* Returns the series.
*
* @return string
*/
public function getSeries();
/**
* Returns the token value.
*
* @return string
*/
public function getTokenValue();
/**
* Returns the time the token was last used.
*
* @return \DateTime
*/
public function getLastUsed();
/**
* @return string
*
* @deprecated since Symfony 5.3, use getUserIdentifier() instead
*/
public function getUsername();
}

View File

@ -0,0 +1,48 @@
<?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\Authentication\RememberMe;
use Symfony\Component\Security\Core\Exception\TokenNotFoundException;
/**
* Interface for TokenProviders.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
interface TokenProviderInterface
{
/**
* Loads the active token for the given series.
*
* @return PersistentTokenInterface
*
* @throws TokenNotFoundException if the token is not found
*/
public function loadTokenBySeries(string $series);
/**
* Deletes all tokens belonging to series.
*/
public function deleteTokenBySeries(string $series);
/**
* Updates the token according to this data.
*
* @throws TokenNotFoundException if the token is not found
*/
public function updateToken(string $series, string $tokenValue, \DateTime $lastUsed);
/**
* Creates a new token.
*/
public function createNewToken(PersistentTokenInterface $token);
}

View File

@ -0,0 +1,32 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Security\Core\Authentication\RememberMe;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
interface TokenVerifierInterface
{
/**
* Verifies that the given $token is valid.
*
* This lets you override the token check logic to for example accept slightly outdated tokens.
*
* Do not forget to implement token comparisons using hash_equals for a secure implementation.
*/
public function verifyToken(PersistentTokenInterface $token, string $tokenValue): bool;
/**
* Updates an existing token with a new token value and lastUsed time.
*/
public function updateExistingToken(PersistentTokenInterface $token, string $tokenValue, \DateTimeInterface $lastUsed): void;
}

View File

@ -0,0 +1,332 @@
<?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\Authentication\Token;
use Symfony\Component\Security\Core\User\EquatableInterface;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* Base class for Token instances.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
abstract class AbstractToken implements TokenInterface
{
private $user;
private $roleNames = [];
private $authenticated = false;
private $attributes = [];
/**
* @param string[] $roles An array of roles
*
* @throws \InvalidArgumentException
*/
public function __construct(array $roles = [])
{
foreach ($roles as $role) {
$this->roleNames[] = $role;
}
}
/**
* {@inheritdoc}
*/
public function getRoleNames(): array
{
return $this->roleNames;
}
/**
* {@inheritdoc}
*/
public function getUsername(/* $legacy = true */)
{
if (1 === \func_num_args() && false === func_get_arg(0)) {
return null;
}
trigger_deprecation('symfony/security-core', '5.3', 'Method "%s()" is deprecated, use getUserIdentifier() instead.', __METHOD__);
if ($this->user instanceof UserInterface) {
return method_exists($this->user, 'getUserIdentifier') ? $this->user->getUserIdentifier() : $this->user->getUsername();
}
return (string) $this->user;
}
/**
* {@inheritdoc}
*/
public function getUserIdentifier(): string
{
// method returns "null" in non-legacy mode if not overridden
$username = $this->getUsername(false);
if (null !== $username) {
trigger_deprecation('symfony/security-core', '5.3', 'Method "%s::getUsername()" is deprecated, override "getUserIdentifier()" instead.', get_debug_type($this));
}
if ($this->user instanceof UserInterface) {
// @deprecated since Symfony 5.3, change to $user->getUserIdentifier() in 6.0
return method_exists($this->user, 'getUserIdentifier') ? $this->user->getUserIdentifier() : $this->user->getUsername();
}
return (string) $this->user;
}
/**
* {@inheritdoc}
*/
public function getUser()
{
return $this->user;
}
/**
* {@inheritdoc}
*/
public function setUser($user)
{
if (!($user instanceof UserInterface || (\is_object($user) && method_exists($user, '__toString')) || \is_string($user))) {
throw new \InvalidArgumentException('$user must be an instanceof UserInterface, an object implementing a __toString method, or a primitive string.');
}
if (!$user instanceof UserInterface) {
trigger_deprecation('symfony/security-core', '5.4', 'Using an object that is not an instance of "%s" as $user in "%s" is deprecated.', UserInterface::class, static::class);
}
// @deprecated since Symfony 5.4, remove the whole block if/elseif/else block in 6.0
if (1 < \func_num_args() && !func_get_arg(1)) {
// ContextListener checks if the user has changed on its own and calls `setAuthenticated()` subsequently,
// avoid doing the same checks twice
$changed = false;
} elseif (null === $this->user) {
$changed = false;
} elseif ($this->user instanceof UserInterface) {
if (!$user instanceof UserInterface) {
$changed = true;
} else {
$changed = $this->hasUserChanged($user);
}
} elseif ($user instanceof UserInterface) {
$changed = true;
} else {
$changed = (string) $this->user !== (string) $user;
}
// @deprecated since Symfony 5.4
if ($changed) {
$this->setAuthenticated(false, false);
}
$this->user = $user;
}
/**
* {@inheritdoc}
*
* @deprecated since Symfony 5.4
*/
public function isAuthenticated()
{
if (1 > \func_num_args() || func_get_arg(0)) {
trigger_deprecation('symfony/security-core', '5.4', 'Method "%s()" is deprecated, return null from "getUser()" instead when a token is not authenticated.', __METHOD__);
}
return $this->authenticated;
}
/**
* {@inheritdoc}
*/
public function setAuthenticated(bool $authenticated)
{
if (2 > \func_num_args() || func_get_arg(1)) {
trigger_deprecation('symfony/security-core', '5.4', 'Method "%s()" is deprecated', __METHOD__);
}
$this->authenticated = $authenticated;
}
/**
* {@inheritdoc}
*/
public function eraseCredentials()
{
if ($this->getUser() instanceof UserInterface) {
$this->getUser()->eraseCredentials();
}
}
/**
* Returns all the necessary state of the object for serialization purposes.
*
* There is no need to serialize any entry, they should be returned as-is.
* If you extend this method, keep in mind you MUST guarantee parent data is present in the state.
* Here is an example of how to extend this method:
* <code>
* public function __serialize(): array
* {
* return [$this->childAttribute, parent::__serialize()];
* }
* </code>
*
* @see __unserialize()
*/
public function __serialize(): array
{
return [$this->user, $this->authenticated, null, $this->attributes, $this->roleNames];
}
/**
* Restores the object state from an array given by __serialize().
*
* There is no need to unserialize any entry in $data, they are already ready-to-use.
* If you extend this method, keep in mind you MUST pass the parent data to its respective class.
* Here is an example of how to extend this method:
* <code>
* public function __unserialize(array $data): void
* {
* [$this->childAttribute, $parentData] = $data;
* parent::__unserialize($parentData);
* }
* </code>
*
* @see __serialize()
*/
public function __unserialize(array $data): void
{
[$this->user, $this->authenticated, , $this->attributes, $this->roleNames] = $data;
}
/**
* {@inheritdoc}
*/
public function getAttributes()
{
return $this->attributes;
}
/**
* {@inheritdoc}
*/
public function setAttributes(array $attributes)
{
$this->attributes = $attributes;
}
/**
* {@inheritdoc}
*/
public function hasAttribute(string $name)
{
return \array_key_exists($name, $this->attributes);
}
/**
* {@inheritdoc}
*/
public function getAttribute(string $name)
{
if (!\array_key_exists($name, $this->attributes)) {
throw new \InvalidArgumentException(sprintf('This token has no "%s" attribute.', $name));
}
return $this->attributes[$name];
}
/**
* {@inheritdoc}
*/
public function setAttribute(string $name, $value)
{
$this->attributes[$name] = $value;
}
/**
* {@inheritdoc}
*/
public function __toString()
{
$class = static::class;
$class = substr($class, strrpos($class, '\\') + 1);
$roles = [];
foreach ($this->roleNames as $role) {
$roles[] = $role;
}
return sprintf('%s(user="%s", authenticated=%s, roles="%s")', $class, $this->getUserIdentifier(), json_encode($this->authenticated), implode(', ', $roles));
}
/**
* @internal
*/
final public function serialize(): string
{
return serialize($this->__serialize());
}
/**
* @internal
*/
final public function unserialize($serialized)
{
$this->__unserialize(\is_array($serialized) ? $serialized : unserialize($serialized));
}
/**
* @deprecated since Symfony 5.4
*/
private function hasUserChanged(UserInterface $user): bool
{
if (!($this->user instanceof UserInterface)) {
throw new \BadMethodCallException('Method "hasUserChanged" should be called when current user class is instance of "UserInterface".');
}
if ($this->user instanceof EquatableInterface) {
return !(bool) $this->user->isEqualTo($user);
}
// @deprecated since Symfony 5.3, check for PasswordAuthenticatedUserInterface on both user objects before comparing passwords
if ($this->user->getPassword() !== $user->getPassword()) {
return true;
}
// @deprecated since Symfony 5.3, check for LegacyPasswordAuthenticatedUserInterface on both user objects before comparing salts
if ($this->user->getSalt() !== $user->getSalt()) {
return true;
}
$userRoles = array_map('strval', (array) $user->getRoles());
if ($this instanceof SwitchUserToken) {
$userRoles[] = 'ROLE_PREVIOUS_ADMIN';
}
if (\count($userRoles) !== \count($this->getRoleNames()) || \count($userRoles) !== \count(array_intersect($userRoles, $this->getRoleNames()))) {
return true;
}
// @deprecated since Symfony 5.3, drop getUsername() in 6.0
$userIdentifier = function ($user) {
return method_exists($user, 'getUserIdentifier') ? $user->getUserIdentifier() : $user->getUsername();
};
if ($userIdentifier($this->user) !== $userIdentifier($user)) {
return true;
}
return false;
}
}

View File

@ -0,0 +1,79 @@
<?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\Authentication\Token;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* AnonymousToken represents an anonymous token.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated since 5.4, anonymous is now represented by the absence of a token
*/
class AnonymousToken extends AbstractToken
{
private $secret;
/**
* @param string $secret A secret used to make sure the token is created by the app and not by a malicious client
* @param string|\Stringable|UserInterface $user
* @param string[] $roles
*/
public function __construct(string $secret, $user, array $roles = [])
{
trigger_deprecation('symfony/security-core', '5.4', 'The "%s" class is deprecated.', __CLASS__);
parent::__construct($roles);
$this->secret = $secret;
$this->setUser($user);
// @deprecated since Symfony 5.4
$this->setAuthenticated(true, false);
}
/**
* {@inheritdoc}
*/
public function getCredentials()
{
return '';
}
/**
* Returns the secret.
*
* @return string
*/
public function getSecret()
{
return $this->secret;
}
/**
* {@inheritdoc}
*/
public function __serialize(): array
{
return [$this->secret, parent::__serialize()];
}
/**
* {@inheritdoc}
*/
public function __unserialize(array $data): void
{
[$this->secret, $parentData] = $data;
$parentData = \is_array($parentData) ? $parentData : unserialize($parentData);
parent::__unserialize($parentData);
}
}

View File

@ -0,0 +1,134 @@
<?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\Authentication\Token;
/**
* @author Wouter de Jong <wouter@wouterj.nl>
*/
class NullToken implements TokenInterface
{
public function __toString(): string
{
return '';
}
public function getRoleNames(): array
{
return [];
}
public function getCredentials()
{
return '';
}
public function getUser()
{
return null;
}
public function setUser($user)
{
throw new \BadMethodCallException('Cannot set user on a NullToken.');
}
public function getUsername()
{
trigger_deprecation('symfony/security-core', '5.3', 'Method "%s()" is deprecated, use getUserIdentifier() instead.', __METHOD__);
return '';
}
public function getUserIdentifier(): string
{
return '';
}
/**
* @deprecated since Symfony 5.4
*/
public function isAuthenticated()
{
if (0 === \func_num_args() || func_get_arg(0)) {
trigger_deprecation('symfony/security-core', '5.4', 'Method "%s()" is deprecated, return null from "getUser()" instead when a token is not authenticated.', __METHOD__);
}
return true;
}
/**
* @deprecated since Symfony 5.4
*/
public function setAuthenticated(bool $isAuthenticated)
{
throw new \BadMethodCallException('Cannot change authentication state of NullToken.');
}
public function eraseCredentials()
{
}
public function getAttributes()
{
return [];
}
public function setAttributes(array $attributes)
{
throw new \BadMethodCallException('Cannot set attributes of NullToken.');
}
public function hasAttribute(string $name)
{
return false;
}
public function getAttribute(string $name)
{
return null;
}
public function setAttribute(string $name, $value)
{
throw new \BadMethodCallException('Cannot add attribute to NullToken.');
}
public function __serialize(): array
{
return [];
}
public function __unserialize(array $data): void
{
}
/**
* @return string
*
* @internal in 5.3
* @final in 5.3
*/
public function serialize()
{
return '';
}
/**
* @return void
*
* @internal in 5.3
* @final in 5.3
*/
public function unserialize($serialized)
{
}
}

View File

@ -0,0 +1,114 @@
<?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\Authentication\Token;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* PreAuthenticatedToken implements a pre-authenticated token.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class PreAuthenticatedToken extends AbstractToken
{
private $credentials;
private $firewallName;
/**
* @param UserInterface $user
* @param string $firewallName
* @param string[] $roles
*/
public function __construct($user, /*string*/ $firewallName, /*array*/ $roles = [])
{
if (\is_string($roles)) {
trigger_deprecation('symfony/security-core', '5.4', 'Argument $credentials of "%s()" is deprecated.', __METHOD__);
$credentials = $firewallName;
$firewallName = $roles;
$roles = \func_num_args() > 3 ? func_get_arg(3) : [];
}
parent::__construct($roles);
if ('' === $firewallName) {
throw new \InvalidArgumentException('$firewallName must not be empty.');
}
$this->setUser($user);
$this->credentials = $credentials ?? null;
$this->firewallName = $firewallName;
if ($roles) {
$this->setAuthenticated(true, false);
}
}
/**
* Returns the provider key.
*
* @return string The provider key
*
* @deprecated since Symfony 5.2, use getFirewallName() instead
*/
public function getProviderKey()
{
if (1 !== \func_num_args() || true !== func_get_arg(0)) {
trigger_deprecation('symfony/security-core', '5.2', 'Method "%s()" is deprecated, use "getFirewallName()" instead.', __METHOD__);
}
return $this->firewallName;
}
public function getFirewallName(): string
{
return $this->getProviderKey(true);
}
/**
* {@inheritdoc}
*/
public function getCredentials()
{
trigger_deprecation('symfony/security-core', '5.4', 'Method "%s()" is deprecated.', __METHOD__);
return $this->credentials;
}
/**
* {@inheritdoc}
*/
public function eraseCredentials()
{
parent::eraseCredentials();
$this->credentials = null;
}
/**
* {@inheritdoc}
*/
public function __serialize(): array
{
return [$this->credentials, $this->firewallName, parent::__serialize()];
}
/**
* {@inheritdoc}
*/
public function __unserialize(array $data): void
{
[$this->credentials, $this->firewallName, $parentData] = $data;
$parentData = \is_array($parentData) ? $parentData : unserialize($parentData);
parent::__unserialize($parentData);
}
}

View File

@ -0,0 +1,118 @@
<?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\Authentication\Token;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* Authentication Token for "Remember-Me".
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
class RememberMeToken extends AbstractToken
{
private $secret;
private $firewallName;
/**
* @param string $secret A secret used to make sure the token is created by the app and not by a malicious client
*
* @throws \InvalidArgumentException
*/
public function __construct(UserInterface $user, string $firewallName, string $secret)
{
parent::__construct($user->getRoles());
if (empty($secret)) {
throw new \InvalidArgumentException('$secret must not be empty.');
}
if ('' === $firewallName) {
throw new \InvalidArgumentException('$firewallName must not be empty.');
}
$this->firewallName = $firewallName;
$this->secret = $secret;
$this->setUser($user);
parent::setAuthenticated(true, false);
}
/**
* {@inheritdoc}
*/
public function setAuthenticated(bool $authenticated)
{
if ($authenticated) {
throw new \LogicException('You cannot set this token to authenticated after creation.');
}
parent::setAuthenticated(false, false);
}
/**
* Returns the provider secret.
*
* @return string The provider secret
*
* @deprecated since Symfony 5.2, use getFirewallName() instead
*/
public function getProviderKey()
{
if (1 !== \func_num_args() || true !== func_get_arg(0)) {
trigger_deprecation('symfony/security-core', '5.2', 'Method "%s()" is deprecated, use "getFirewallName()" instead.', __METHOD__);
}
return $this->firewallName;
}
public function getFirewallName(): string
{
return $this->getProviderKey(true);
}
/**
* @return string
*/
public function getSecret()
{
return $this->secret;
}
/**
* {@inheritdoc}
*/
public function getCredentials()
{
trigger_deprecation('symfony/security-core', '5.4', 'Method "%s()" is deprecated.', __METHOD__);
return '';
}
/**
* {@inheritdoc}
*/
public function __serialize(): array
{
return [$this->secret, $this->firewallName, parent::__serialize()];
}
/**
* {@inheritdoc}
*/
public function __unserialize(array $data): void
{
[$this->secret, $this->firewallName, $parentData] = $data;
$parentData = \is_array($parentData) ? $parentData : unserialize($parentData);
parent::__unserialize($parentData);
}
}

View File

@ -0,0 +1,71 @@
<?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\Authentication\Token\Storage;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Contracts\Service\ResetInterface;
/**
* TokenStorage contains a TokenInterface.
*
* It gives access to the token representing the current user authentication.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
class TokenStorage implements TokenStorageInterface, ResetInterface
{
private $token;
private $initializer;
/**
* {@inheritdoc}
*/
public function getToken()
{
if ($initializer = $this->initializer) {
$this->initializer = null;
$initializer();
}
return $this->token;
}
/**
* {@inheritdoc}
*/
public function setToken(TokenInterface $token = null)
{
if ($token) {
// ensure any initializer is called
$this->getToken();
// @deprecated since Symfony 5.3
if (!method_exists($token, 'getUserIdentifier')) {
trigger_deprecation('symfony/security-core', '5.3', 'Not implementing method "getUserIdentifier(): string" in token class "%s" is deprecated. This method will replace "getUsername()" in Symfony 6.0.', get_debug_type($token));
}
}
$this->initializer = null;
$this->token = $token;
}
public function setInitializer(?callable $initializer): void
{
$this->initializer = $initializer;
}
public function reset()
{
$this->setToken(null);
}
}

View File

@ -0,0 +1,36 @@
<?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\Authentication\Token\Storage;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
/**
* The TokenStorageInterface.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
interface TokenStorageInterface
{
/**
* Returns the current security token.
*
* @return TokenInterface|null
*/
public function getToken();
/**
* Sets the authentication token.
*
* @param TokenInterface|null $token A TokenInterface token, or null if no further authentication information should be stored
*/
public function setToken(TokenInterface $token = null);
}

View File

@ -0,0 +1,109 @@
<?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\Authentication\Token\Storage;
use Psr\Container\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Contracts\Service\ServiceSubscriberInterface;
/**
* A token storage that increments the session usage index when the token is accessed.
*
* @author Nicolas Grekas <p@tchwork.com>
*/
final class UsageTrackingTokenStorage implements TokenStorageInterface, ServiceSubscriberInterface
{
private $storage;
private $container;
private $enableUsageTracking = false;
public function __construct(TokenStorageInterface $storage, ContainerInterface $container)
{
$this->storage = $storage;
$this->container = $container;
}
/**
* {@inheritdoc}
*/
public function getToken(): ?TokenInterface
{
if ($this->shouldTrackUsage()) {
// increments the internal session usage index
$this->getSession()->getMetadataBag();
}
return $this->storage->getToken();
}
/**
* {@inheritdoc}
*/
public function setToken(TokenInterface $token = null): void
{
$this->storage->setToken($token);
if ($token && $this->shouldTrackUsage()) {
// increments the internal session usage index
$this->getSession()->getMetadataBag();
}
}
public function enableUsageTracking(): void
{
$this->enableUsageTracking = true;
}
public function disableUsageTracking(): void
{
$this->enableUsageTracking = false;
}
public static function getSubscribedServices(): array
{
return [
'request_stack' => RequestStack::class,
];
}
private function getSession(): SessionInterface
{
// BC for symfony/security-bundle < 5.3
if ($this->container->has('session')) {
trigger_deprecation('symfony/security-core', '5.3', 'Injecting the "session" in "%s" is deprecated, inject the "request_stack" instead.', __CLASS__);
return $this->container->get('session');
}
return $this->container->get('request_stack')->getSession();
}
private function shouldTrackUsage(): bool
{
if (!$this->enableUsageTracking) {
return false;
}
// BC for symfony/security-bundle < 5.3
if ($this->container->has('session')) {
return true;
}
if (!$this->container->get('request_stack')->getMainRequest()) {
return false;
}
return true;
}
}

View File

@ -0,0 +1,87 @@
<?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\Authentication\Token;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* Token representing a user who temporarily impersonates another one.
*
* @author Christian Flothmann <christian.flothmann@sensiolabs.de>
*/
class SwitchUserToken extends UsernamePasswordToken
{
private $originalToken;
private $originatedFromUri;
/**
* @param UserInterface $user
* @param string|null $originatedFromUri The URI where was the user at the switch
*
* @throws \InvalidArgumentException
*/
public function __construct($user, /*string*/ $firewallName, /*array*/ $roles, /*TokenInterface*/ $originalToken, /*string*/ $originatedFromUri = null)
{
if (\is_string($roles)) {
// @deprecated since 5.4, deprecation is triggered by UsernamePasswordToken::__construct()
$credentials = $firewallName;
$firewallName = $roles;
$roles = $originalToken;
$originalToken = $originatedFromUri;
$originatedFromUri = \func_num_args() > 5 ? func_get_arg(5) : null;
parent::__construct($user, $credentials, $firewallName, $roles);
} else {
parent::__construct($user, $firewallName, $roles);
}
if (!$originalToken instanceof TokenInterface) {
throw new \TypeError(sprintf('Argument $originalToken of "%s" must be an instance of "%s", "%s" given.', __METHOD__, TokenInterface::class, get_debug_type($originalToken)));
}
$this->originalToken = $originalToken;
$this->originatedFromUri = $originatedFromUri;
}
public function getOriginalToken(): TokenInterface
{
return $this->originalToken;
}
public function getOriginatedFromUri(): ?string
{
return $this->originatedFromUri;
}
/**
* {@inheritdoc}
*/
public function __serialize(): array
{
return [$this->originalToken, $this->originatedFromUri, parent::__serialize()];
}
/**
* {@inheritdoc}
*/
public function __unserialize(array $data): void
{
if (3 > \count($data)) {
// Support for tokens serialized with version 5.1 or lower of symfony/security-core.
[$this->originalToken, $parentData] = $data;
} else {
[$this->originalToken, $this->originatedFromUri, $parentData] = $data;
}
$parentData = \is_array($parentData) ? $parentData : unserialize($parentData);
parent::__unserialize($parentData);
}
}

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\Authentication\Token;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* TokenInterface is the interface for the user authentication information.
*
* @method string getUserIdentifier() returns the user identifier used during authentication (e.g. a user's email address or username)
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
interface TokenInterface extends \Serializable
{
/**
* Returns a string representation of the Token.
*
* This is only to be used for debugging purposes.
*
* @return string
*/
public function __toString();
/**
* Returns the user roles.
*
* @return string[]
*/
public function getRoleNames(): array;
/**
* Returns the user credentials.
*
* @return mixed
*
* @deprecated since Symfony 5.4
*/
public function getCredentials();
/**
* Returns a user representation.
*
* @return UserInterface|null
*
* @see AbstractToken::setUser()
*/
public function getUser();
/**
* Sets the authenticated user in the token.
*
* @param UserInterface $user
*
* @throws \InvalidArgumentException
*/
public function setUser($user);
/**
* Returns whether the user is authenticated or not.
*
* @return bool true if the token has been authenticated, false otherwise
*
* @deprecated since Symfony 5.4, return null from "getUser()" instead when a token is not authenticated
*/
public function isAuthenticated();
/**
* Sets the authenticated flag.
*
* @deprecated since Symfony 5.4
*/
public function setAuthenticated(bool $isAuthenticated);
/**
* Removes sensitive information from the token.
*/
public function eraseCredentials();
/**
* @return array
*/
public function getAttributes();
/**
* @param array $attributes The token attributes
*/
public function setAttributes(array $attributes);
/**
* @return bool
*/
public function hasAttribute(string $name);
/**
* @return mixed
*
* @throws \InvalidArgumentException When attribute doesn't exist for this token
*/
public function getAttribute(string $name);
/**
* @param mixed $value The attribute value
*/
public function setAttribute(string $name, $value);
/**
* Returns all the necessary state of the object for serialization purposes.
*/
public function __serialize(): array;
/**
* Restores the object state from an array given by __serialize().
*/
public function __unserialize(array $data): void;
/**
* @return string
*
* @deprecated since Symfony 5.3, use getUserIdentifier() instead
*/
public function getUsername();
}

View File

@ -0,0 +1,125 @@
<?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\Authentication\Token;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* UsernamePasswordToken implements a username and password token.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class UsernamePasswordToken extends AbstractToken
{
private $credentials;
private $firewallName;
/**
* @param UserInterface $user
* @param string[] $roles
*
* @throws \InvalidArgumentException
*/
public function __construct($user, /*string*/ $firewallName, /*array*/ $roles = [])
{
if (\is_string($roles)) {
trigger_deprecation('symfony/security-core', '5.4', 'The $credentials argument of "%s" is deprecated.', static::class.'::__construct');
$credentials = $firewallName;
$firewallName = $roles;
$roles = \func_num_args() > 3 ? func_get_arg(3) : [];
}
parent::__construct($roles);
if ('' === $firewallName) {
throw new \InvalidArgumentException('$firewallName must not be empty.');
}
$this->setUser($user);
$this->credentials = $credentials ?? null;
$this->firewallName = $firewallName;
parent::setAuthenticated(\count($roles) > 0, false);
}
/**
* {@inheritdoc}
*/
public function setAuthenticated(bool $isAuthenticated)
{
if ($isAuthenticated) {
throw new \LogicException('Cannot set this token to trusted after instantiation.');
}
parent::setAuthenticated(false, false);
}
/**
* {@inheritdoc}
*/
public function getCredentials()
{
trigger_deprecation('symfony/security-core', '5.4', 'Method "%s" is deprecated.', __METHOD__);
return $this->credentials;
}
/**
* Returns the provider key.
*
* @return string The provider key
*
* @deprecated since Symfony 5.2, use getFirewallName() instead
*/
public function getProviderKey()
{
if (1 !== \func_num_args() || true !== func_get_arg(0)) {
trigger_deprecation('symfony/security-core', '5.2', 'Method "%s" is deprecated, use "getFirewallName()" instead.', __METHOD__);
}
return $this->firewallName;
}
public function getFirewallName(): string
{
return $this->getProviderKey(true);
}
/**
* {@inheritdoc}
*/
public function eraseCredentials()
{
parent::eraseCredentials();
$this->credentials = null;
}
/**
* {@inheritdoc}
*/
public function __serialize(): array
{
return [$this->credentials, $this->firewallName, parent::__serialize()];
}
/**
* {@inheritdoc}
*/
public function __unserialize(array $data): void
{
[$this->credentials, $this->firewallName, $parentData] = $data;
$parentData = \is_array($parentData) ? $parentData : unserialize($parentData);
parent::__unserialize($parentData);
}
}

View File

@ -0,0 +1,46 @@
<?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;
use Symfony\Component\Security\Core\Event\AuthenticationFailureEvent;
use Symfony\Component\Security\Core\Event\AuthenticationSuccessEvent;
final class AuthenticationEvents
{
/**
* The AUTHENTICATION_SUCCESS event occurs after a user is authenticated
* by one provider.
*
* @Event("Symfony\Component\Security\Core\Event\AuthenticationSuccessEvent")
*/
public const AUTHENTICATION_SUCCESS = 'security.authentication.success';
/**
* The AUTHENTICATION_FAILURE event occurs after a user cannot be
* authenticated by any of the providers.
*
* @Event("Symfony\Component\Security\Core\Event\AuthenticationFailureEvent")
*
* @deprecated since Symfony 5.4, use {@see Event\LoginFailureEvent} instead
*/
public const AUTHENTICATION_FAILURE = 'security.authentication.failure';
/**
* Event aliases.
*
* These aliases can be consumed by RegisterListenersPass.
*/
public const ALIASES = [
AuthenticationSuccessEvent::class => self::AUTHENTICATION_SUCCESS,
AuthenticationFailureEvent::class => self::AUTHENTICATION_FAILURE,
];
}

View File

@ -0,0 +1,188 @@
<?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\Authorization;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Strategy\AccessDecisionStrategyInterface;
use Symfony\Component\Security\Core\Authorization\Strategy\AffirmativeStrategy;
use Symfony\Component\Security\Core\Authorization\Strategy\ConsensusStrategy;
use Symfony\Component\Security\Core\Authorization\Strategy\PriorityStrategy;
use Symfony\Component\Security\Core\Authorization\Strategy\UnanimousStrategy;
use Symfony\Component\Security\Core\Authorization\Voter\CacheableVoterInterface;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
use Symfony\Component\Security\Core\Exception\InvalidArgumentException;
/**
* AccessDecisionManager is the base class for all access decision managers
* that use decision voters.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @final since Symfony 5.4
*/
class AccessDecisionManager implements AccessDecisionManagerInterface
{
/**
* @deprecated use {@see AffirmativeStrategy} instead
*/
public const STRATEGY_AFFIRMATIVE = 'affirmative';
/**
* @deprecated use {@see ConsensusStrategy} instead
*/
public const STRATEGY_CONSENSUS = 'consensus';
/**
* @deprecated use {@see UnanimousStrategy} instead
*/
public const STRATEGY_UNANIMOUS = 'unanimous';
/**
* @deprecated use {@see PriorityStrategy} instead
*/
public const STRATEGY_PRIORITY = 'priority';
private const VALID_VOTES = [
VoterInterface::ACCESS_GRANTED => true,
VoterInterface::ACCESS_DENIED => true,
VoterInterface::ACCESS_ABSTAIN => true,
];
private $voters;
private $votersCacheAttributes;
private $votersCacheObject;
private $strategy;
/**
* @param iterable<mixed, VoterInterface> $voters An array or an iterator of VoterInterface instances
* @param AccessDecisionStrategyInterface|null $strategy The vote strategy
*
* @throws \InvalidArgumentException
*/
public function __construct(iterable $voters = [], /* AccessDecisionStrategyInterface */ $strategy = null)
{
$this->voters = $voters;
if (\is_string($strategy)) {
trigger_deprecation('symfony/security-core', '5.4', 'Passing the access decision strategy as a string is deprecated, pass an instance of "%s" instead.', AccessDecisionStrategyInterface::class);
$allowIfAllAbstainDecisions = 3 <= \func_num_args() && func_get_arg(2);
$allowIfEqualGrantedDeniedDecisions = 4 > \func_num_args() || func_get_arg(3);
$strategy = $this->createStrategy($strategy, $allowIfAllAbstainDecisions, $allowIfEqualGrantedDeniedDecisions);
} elseif (null !== $strategy && !$strategy instanceof AccessDecisionStrategyInterface) {
throw new \TypeError(sprintf('"%s": Parameter #2 ($strategy) is expected to be an instance of "%s" or null, "%s" given.', __METHOD__, AccessDecisionStrategyInterface::class, get_debug_type($strategy)));
}
$this->strategy = $strategy ?? new AffirmativeStrategy();
}
/**
* @param bool $allowMultipleAttributes Whether to allow passing multiple values to the $attributes array
*
* {@inheritdoc}
*/
public function decide(TokenInterface $token, array $attributes, $object = null/*, bool $allowMultipleAttributes = false*/)
{
$allowMultipleAttributes = 3 < \func_num_args() && func_get_arg(3);
// Special case for AccessListener, do not remove the right side of the condition before 6.0
if (\count($attributes) > 1 && !$allowMultipleAttributes) {
throw new InvalidArgumentException(sprintf('Passing more than one Security attribute to "%s()" is not supported.', __METHOD__));
}
return $this->strategy->decide(
$this->collectResults($token, $attributes, $object)
);
}
/**
* @param mixed $object
*
* @return \Traversable<int, int>
*/
private function collectResults(TokenInterface $token, array $attributes, $object): \Traversable
{
foreach ($this->getVoters($attributes, $object) as $voter) {
$result = $voter->vote($token, $object, $attributes);
if (!\is_int($result) || !(self::VALID_VOTES[$result] ?? false)) {
trigger_deprecation('symfony/security-core', '5.3', 'Returning "%s" in "%s::vote()" is deprecated, return one of "%s" constants: "ACCESS_GRANTED", "ACCESS_DENIED" or "ACCESS_ABSTAIN".', var_export($result, true), get_debug_type($voter), VoterInterface::class);
}
yield $result;
}
}
/**
* @throws \InvalidArgumentException if the $strategy is invalid
*/
private function createStrategy(string $strategy, bool $allowIfAllAbstainDecisions, bool $allowIfEqualGrantedDeniedDecisions): AccessDecisionStrategyInterface
{
switch ($strategy) {
case self::STRATEGY_AFFIRMATIVE:
return new AffirmativeStrategy($allowIfAllAbstainDecisions);
case self::STRATEGY_CONSENSUS:
return new ConsensusStrategy($allowIfAllAbstainDecisions, $allowIfEqualGrantedDeniedDecisions);
case self::STRATEGY_UNANIMOUS:
return new UnanimousStrategy($allowIfAllAbstainDecisions);
case self::STRATEGY_PRIORITY:
return new PriorityStrategy($allowIfAllAbstainDecisions);
}
throw new \InvalidArgumentException(sprintf('The strategy "%s" is not supported.', $strategy));
}
/**
* @return iterable<mixed, VoterInterface>
*/
private function getVoters(array $attributes, $object = null): iterable
{
$keyAttributes = [];
foreach ($attributes as $attribute) {
$keyAttributes[] = \is_string($attribute) ? $attribute : null;
}
// use `get_class` to handle anonymous classes
$keyObject = \is_object($object) ? \get_class($object) : get_debug_type($object);
foreach ($this->voters as $key => $voter) {
if (!$voter instanceof CacheableVoterInterface) {
yield $voter;
continue;
}
$supports = true;
// The voter supports the attributes if it supports at least one attribute of the list
foreach ($keyAttributes as $keyAttribute) {
if (null === $keyAttribute) {
$supports = true;
} elseif (!isset($this->votersCacheAttributes[$keyAttribute][$key])) {
$this->votersCacheAttributes[$keyAttribute][$key] = $supports = $voter->supportsAttribute($keyAttribute);
} else {
$supports = $this->votersCacheAttributes[$keyAttribute][$key];
}
if ($supports) {
break;
}
}
if (!$supports) {
continue;
}
if (!isset($this->votersCacheObject[$keyObject][$key])) {
$this->votersCacheObject[$keyObject][$key] = $supports = $voter->supportsType($keyObject);
} else {
$supports = $this->votersCacheObject[$keyObject][$key];
}
if (!$supports) {
continue;
}
yield $voter;
}
}
}

View File

@ -0,0 +1,32 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Security\Core\Authorization;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
/**
* AccessDecisionManagerInterface makes authorization decisions.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
interface AccessDecisionManagerInterface
{
/**
* Decides whether the access is possible or not.
*
* @param array $attributes An array of attributes associated with the method being invoked
* @param mixed $object The object to secure
*
* @return bool
*/
public function decide(TokenInterface $token, array $attributes, $object = null);
}

View File

@ -0,0 +1,91 @@
<?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\Authorization;
use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\NullToken;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException;
/**
* AuthorizationChecker is the main authorization point of the Security component.
*
* It gives access to the token representing the current user authentication.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
class AuthorizationChecker implements AuthorizationCheckerInterface
{
private $tokenStorage;
private $accessDecisionManager;
private $authenticationManager;
private $alwaysAuthenticate;
private $exceptionOnNoToken;
public function __construct(TokenStorageInterface $tokenStorage, /*AccessDecisionManagerInterface*/ $accessDecisionManager, /*bool*/ $alwaysAuthenticate = false, /*bool*/ $exceptionOnNoToken = true)
{
if ($accessDecisionManager instanceof AuthenticationManagerInterface) {
trigger_deprecation('symfony/security-core', '5.4', 'The $autenticationManager argument of "%s" is deprecated.', __METHOD__);
$this->authenticationManager = $accessDecisionManager;
$accessDecisionManager = $alwaysAuthenticate;
$alwaysAuthenticate = $exceptionOnNoToken;
$exceptionOnNoToken = \func_num_args() > 4 ? func_get_arg(4) : true;
}
if (false !== $alwaysAuthenticate) {
trigger_deprecation('symfony/security-core', '5.4', 'Not setting the 4th argument of "%s" to "false" is deprecated.', __METHOD__);
}
if (false !== $exceptionOnNoToken) {
trigger_deprecation('symfony/security-core', '5.4', 'Not setting the 5th argument of "%s" to "false" is deprecated.', __METHOD__);
}
if (!$accessDecisionManager instanceof AccessDecisionManagerInterface) {
throw new \TypeError(sprintf('Argument 2 of "%s" must be instance of "%s", "%s" given.', __METHOD__, AccessDecisionManagerInterface::class, get_debug_type($accessDecisionManager)));
}
$this->tokenStorage = $tokenStorage;
$this->accessDecisionManager = $accessDecisionManager;
$this->alwaysAuthenticate = $alwaysAuthenticate;
$this->exceptionOnNoToken = $exceptionOnNoToken;
}
/**
* {@inheritdoc}
*
* @throws AuthenticationCredentialsNotFoundException when the token storage has no authentication token and $exceptionOnNoToken is set to true
*/
final public function isGranted($attribute, $subject = null): bool
{
$token = $this->tokenStorage->getToken();
if (!$token || !$token->getUser()) {
if ($this->exceptionOnNoToken) {
throw new AuthenticationCredentialsNotFoundException('The token storage contains no authentication token. One possible reason may be that there is no firewall configured for this URL.');
}
$token = new NullToken();
} else {
$authenticated = true;
// @deprecated since Symfony 5.4
if ($this->alwaysAuthenticate || !$authenticated = $token->isAuthenticated(false)) {
if (!($authenticated ?? true)) {
trigger_deprecation('symfony/core', '5.4', 'Returning false from "%s()" is deprecated, return null from "getUser()" instead.');
}
$this->tokenStorage->setToken($token = $this->authenticationManager->authenticate($token));
}
}
return $this->accessDecisionManager->decide($token, [$attribute], $subject);
}
}

View File

@ -0,0 +1,30 @@
<?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\Authorization;
/**
* The AuthorizationCheckerInterface.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
interface AuthorizationCheckerInterface
{
/**
* Checks if the attribute is granted against the current authentication token and optionally supplied subject.
*
* @param mixed $attribute A single attribute to vote on (can be of any type, string and instance of Expression are supported by the core)
* @param mixed $subject
*
* @return bool
*/
public function isGranted($attribute, $subject = null);
}

View File

@ -0,0 +1,43 @@
<?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\Authorization;
use Psr\Cache\CacheItemPoolInterface;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage as BaseExpressionLanguage;
if (!class_exists(BaseExpressionLanguage::class)) {
throw new \LogicException(sprintf('The "%s" class requires the "ExpressionLanguage" component. Try running "composer require symfony/expression-language".', ExpressionLanguage::class));
} else {
// Help opcache.preload discover always-needed symbols
class_exists(ExpressionLanguageProvider::class);
/**
* Adds some function to the default ExpressionLanguage.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @see ExpressionLanguageProvider
*/
class ExpressionLanguage extends BaseExpressionLanguage
{
/**
* {@inheritdoc}
*/
public function __construct(CacheItemPoolInterface $cache = null, array $providers = [])
{
// prepend the default provider to let users override it easily
array_unshift($providers, new ExpressionLanguageProvider());
parent::__construct($cache, $providers);
}
}
}

View File

@ -0,0 +1,62 @@
<?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\Authorization;
use Symfony\Component\ExpressionLanguage\ExpressionFunction;
use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;
use Symfony\Component\Security\Core\Authorization\Voter\AuthenticatedVoter;
/**
* Define some ExpressionLanguage functions.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class ExpressionLanguageProvider implements ExpressionFunctionProviderInterface
{
public function getFunctions()
{
return [
new ExpressionFunction('is_anonymous', function () {
return 'trigger_deprecation("symfony/security-core", "5.4", "The \"is_anonymous()\" expression function is deprecated.") || ($token && $auth_checker->isGranted("IS_ANONYMOUS"))';
}, function (array $variables) {
trigger_deprecation('symfony/security-core', '5.4', 'The "is_anonymous()" expression function is deprecated.');
return $variables['token'] && $variables['auth_checker']->isGranted('IS_ANONYMOUS');
}),
// @deprecated remove the ternary and always use IS_AUTHENTICATED in 6.0
new ExpressionFunction('is_authenticated', function () {
return 'defined("'.AuthenticatedVoter::class.'::IS_AUTHENTICATED") ? $auth_checker->isGranted("IS_AUTHENTICATED") : ($token && !$auth_checker->isGranted("IS_ANONYMOUS"))';
}, function (array $variables) {
return \defined(AuthenticatedVoter::class.'::IS_AUTHENTICATED') ? $variables['auth_checker']->isGranted('IS_AUTHENTICATED') : ($variables['token'] && !$variables['auth_checker']->isGranted('IS_ANONYMOUS'));
}),
new ExpressionFunction('is_fully_authenticated', function () {
return '$token && $auth_checker->isGranted("IS_AUTHENTICATED_FULLY")';
}, function (array $variables) {
return $variables['token'] && $variables['auth_checker']->isGranted('IS_AUTHENTICATED_FULLY');
}),
new ExpressionFunction('is_granted', function ($attributes, $object = 'null') {
return sprintf('$auth_checker->isGranted(%s, %s)', $attributes, $object);
}, function (array $variables, $attributes, $object = null) {
return $variables['auth_checker']->isGranted($attributes, $object);
}),
new ExpressionFunction('is_remember_me', function () {
return '$token && $auth_checker->isGranted("IS_REMEMBERED")';
}, function (array $variables) {
return $variables['token'] && $variables['auth_checker']->isGranted('IS_REMEMBERED');
}),
];
}
}

View File

@ -0,0 +1,25 @@
<?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\Authorization\Strategy;
/**
* A strategy for turning a stream of votes into a final decision.
*
* @author Alexander M. Turek <me@derrabus.de>
*/
interface AccessDecisionStrategyInterface
{
/**
* @param \Traversable<int> $results
*/
public function decide(\Traversable $results): bool;
}

View File

@ -0,0 +1,64 @@
<?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\Authorization\Strategy;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
/**
* Grants access if any voter returns an affirmative response.
*
* If all voters abstained from voting, the decision will be based on the
* allowIfAllAbstainDecisions property value (defaults to false).
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Alexander M. Turek <me@derrabus.de>
*/
final class AffirmativeStrategy implements AccessDecisionStrategyInterface, \Stringable
{
/**
* @var bool
*/
private $allowIfAllAbstainDecisions;
public function __construct(bool $allowIfAllAbstainDecisions = false)
{
$this->allowIfAllAbstainDecisions = $allowIfAllAbstainDecisions;
}
/**
* {@inheritdoc}
*/
public function decide(\Traversable $results): bool
{
$deny = 0;
foreach ($results as $result) {
if (VoterInterface::ACCESS_GRANTED === $result) {
return true;
}
if (VoterInterface::ACCESS_DENIED === $result) {
++$deny;
}
}
if ($deny > 0) {
return false;
}
return $this->allowIfAllAbstainDecisions;
}
public function __toString(): string
{
return 'affirmative';
}
}

View File

@ -0,0 +1,75 @@
<?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\Authorization\Strategy;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
/**
* Grants access if there is consensus of granted against denied responses.
*
* Consensus means majority-rule (ignoring abstains) rather than unanimous
* agreement (ignoring abstains). If you require unanimity, see
* UnanimousBased.
*
* If there were an equal number of grant and deny votes, the decision will
* be based on the allowIfEqualGrantedDeniedDecisions property value
* (defaults to true).
*
* If all voters abstained from voting, the decision will be based on the
* allowIfAllAbstainDecisions property value (defaults to false).
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Alexander M. Turek <me@derrabus.de>
*/
final class ConsensusStrategy implements AccessDecisionStrategyInterface, \Stringable
{
private $allowIfAllAbstainDecisions;
private $allowIfEqualGrantedDeniedDecisions;
public function __construct(bool $allowIfAllAbstainDecisions = false, bool $allowIfEqualGrantedDeniedDecisions = true)
{
$this->allowIfAllAbstainDecisions = $allowIfAllAbstainDecisions;
$this->allowIfEqualGrantedDeniedDecisions = $allowIfEqualGrantedDeniedDecisions;
}
public function decide(\Traversable $results): bool
{
$grant = 0;
$deny = 0;
foreach ($results as $result) {
if (VoterInterface::ACCESS_GRANTED === $result) {
++$grant;
} elseif (VoterInterface::ACCESS_DENIED === $result) {
++$deny;
}
}
if ($grant > $deny) {
return true;
}
if ($deny > $grant) {
return false;
}
if ($grant > 0) {
return $this->allowIfEqualGrantedDeniedDecisions;
}
return $this->allowIfAllAbstainDecisions;
}
public function __toString(): string
{
return 'consensus';
}
}

View File

@ -0,0 +1,57 @@
<?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\Authorization\Strategy;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
/**
* Grant or deny access depending on the first voter that does not abstain.
* The priority of voters can be used to overrule a decision.
*
* If all voters abstained from voting, the decision will be based on the
* allowIfAllAbstainDecisions property value (defaults to false).
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Alexander M. Turek <me@derrabus.de>
*/
final class PriorityStrategy implements AccessDecisionStrategyInterface, \Stringable
{
private $allowIfAllAbstainDecisions;
public function __construct(bool $allowIfAllAbstainDecisions = false)
{
$this->allowIfAllAbstainDecisions = $allowIfAllAbstainDecisions;
}
/**
* {@inheritdoc}
*/
public function decide(\Traversable $results): bool
{
foreach ($results as $result) {
if (VoterInterface::ACCESS_GRANTED === $result) {
return true;
}
if (VoterInterface::ACCESS_DENIED === $result) {
return false;
}
}
return $this->allowIfAllAbstainDecisions;
}
public function __toString(): string
{
return 'priority';
}
}

View File

@ -0,0 +1,62 @@
<?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\Authorization\Strategy;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
/**
* Grants access if only grant (or abstain) votes were received.
*
* If all voters abstained from voting, the decision will be based on the
* allowIfAllAbstainDecisions property value (defaults to false).
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Alexander M. Turek <me@derrabus.de>
*/
final class UnanimousStrategy implements AccessDecisionStrategyInterface, \Stringable
{
private $allowIfAllAbstainDecisions;
public function __construct(bool $allowIfAllAbstainDecisions = false)
{
$this->allowIfAllAbstainDecisions = $allowIfAllAbstainDecisions;
}
/**
* {@inheritdoc}
*/
public function decide(\Traversable $results): bool
{
$grant = 0;
foreach ($results as $result) {
if (VoterInterface::ACCESS_DENIED === $result) {
return false;
}
if (VoterInterface::ACCESS_GRANTED === $result) {
++$grant;
}
}
// no deny votes
if ($grant > 0) {
return true;
}
return $this->allowIfAllAbstainDecisions;
}
public function __toString(): string
{
return 'unanimous';
}
}

View File

@ -0,0 +1,117 @@
<?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\Authorization;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
/**
* Decorates the original AccessDecisionManager class to log information
* about the security voters and the decisions made by them.
*
* @author Javier Eguiluz <javier.eguiluz@gmail.com>
*
* @internal
*/
class TraceableAccessDecisionManager implements AccessDecisionManagerInterface
{
private $manager;
private $strategy;
/** @var iterable<mixed, VoterInterface> */
private $voters = [];
private $decisionLog = []; // All decision logs
private $currentLog = []; // Logs being filled in
public function __construct(AccessDecisionManagerInterface $manager)
{
$this->manager = $manager;
if ($this->manager instanceof AccessDecisionManager) {
// The strategy and voters are stored in a private properties of the decorated service
$reflection = new \ReflectionProperty(AccessDecisionManager::class, 'strategy');
$reflection->setAccessible(true);
$this->strategy = $reflection->getValue($manager);
$reflection = new \ReflectionProperty(AccessDecisionManager::class, 'voters');
$reflection->setAccessible(true);
$this->voters = $reflection->getValue($manager);
}
}
/**
* {@inheritdoc}
*
* @param bool $allowMultipleAttributes Whether to allow passing multiple values to the $attributes array
*/
public function decide(TokenInterface $token, array $attributes, $object = null/*, bool $allowMultipleAttributes = false*/): bool
{
$currentDecisionLog = [
'attributes' => $attributes,
'object' => $object,
'voterDetails' => [],
];
$this->currentLog[] = &$currentDecisionLog;
$result = $this->manager->decide($token, $attributes, $object, 3 < \func_num_args() && func_get_arg(3));
$currentDecisionLog['result'] = $result;
$this->decisionLog[] = array_pop($this->currentLog); // Using a stack since decide can be called by voters
return $result;
}
/**
* Adds voter vote and class to the voter details.
*
* @param array $attributes attributes used for the vote
* @param int $vote vote of the voter
*/
public function addVoterVote(VoterInterface $voter, array $attributes, int $vote)
{
$currentLogIndex = \count($this->currentLog) - 1;
$this->currentLog[$currentLogIndex]['voterDetails'][] = [
'voter' => $voter,
'attributes' => $attributes,
'vote' => $vote,
];
}
public function getStrategy(): string
{
if (null === $this->strategy) {
return '-';
}
if (method_exists($this->strategy, '__toString')) {
return (string) $this->strategy;
}
return get_debug_type($this->strategy);
}
/**
* @return iterable<mixed, VoterInterface>
*/
public function getVoters(): iterable
{
return $this->voters;
}
public function getDecisionLog(): array
{
return $this->decisionLog;
}
}
if (!class_exists(DebugAccessDecisionManager::class, false)) {
class_alias(TraceableAccessDecisionManager::class, DebugAccessDecisionManager::class);
}

View File

@ -0,0 +1,138 @@
<?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\Authorization\Voter;
use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolverInterface;
use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
/**
* AuthenticatedVoter votes if an attribute like IS_AUTHENTICATED_FULLY,
* IS_AUTHENTICATED_REMEMBERED, IS_AUTHENTICATED is present.
*
* This list is most restrictive to least restrictive checking.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
class AuthenticatedVoter implements CacheableVoterInterface
{
public const IS_AUTHENTICATED_FULLY = 'IS_AUTHENTICATED_FULLY';
public const IS_AUTHENTICATED_REMEMBERED = 'IS_AUTHENTICATED_REMEMBERED';
/**
* @deprecated since Symfony 5.4
*/
public const IS_AUTHENTICATED_ANONYMOUSLY = 'IS_AUTHENTICATED_ANONYMOUSLY';
/**
* @deprecated since Symfony 5.4
*/
public const IS_ANONYMOUS = 'IS_ANONYMOUS';
public const IS_AUTHENTICATED = 'IS_AUTHENTICATED';
public const IS_IMPERSONATOR = 'IS_IMPERSONATOR';
public const IS_REMEMBERED = 'IS_REMEMBERED';
public const PUBLIC_ACCESS = 'PUBLIC_ACCESS';
private $authenticationTrustResolver;
public function __construct(AuthenticationTrustResolverInterface $authenticationTrustResolver)
{
$this->authenticationTrustResolver = $authenticationTrustResolver;
}
/**
* {@inheritdoc}
*/
public function vote(TokenInterface $token, $subject, array $attributes)
{
if ($attributes === [self::PUBLIC_ACCESS]) {
return VoterInterface::ACCESS_GRANTED;
}
$result = VoterInterface::ACCESS_ABSTAIN;
foreach ($attributes as $attribute) {
if (null === $attribute || (self::IS_AUTHENTICATED_FULLY !== $attribute
&& self::IS_AUTHENTICATED_REMEMBERED !== $attribute
&& self::IS_AUTHENTICATED_ANONYMOUSLY !== $attribute
&& self::IS_AUTHENTICATED !== $attribute
&& self::IS_ANONYMOUS !== $attribute
&& self::IS_IMPERSONATOR !== $attribute
&& self::IS_REMEMBERED !== $attribute)) {
continue;
}
$result = VoterInterface::ACCESS_DENIED;
if (self::IS_AUTHENTICATED_FULLY === $attribute
&& $this->authenticationTrustResolver->isFullFledged($token)) {
return VoterInterface::ACCESS_GRANTED;
}
if (self::IS_AUTHENTICATED_REMEMBERED === $attribute
&& ($this->authenticationTrustResolver->isRememberMe($token)
|| $this->authenticationTrustResolver->isFullFledged($token))) {
return VoterInterface::ACCESS_GRANTED;
}
if (self::IS_AUTHENTICATED_ANONYMOUSLY === $attribute
&& ($this->authenticationTrustResolver->isAnonymous($token)
|| $this->authenticationTrustResolver->isRememberMe($token)
|| $this->authenticationTrustResolver->isFullFledged($token))) {
trigger_deprecation('symfony/security-core', '5.4', 'The "IS_AUTHENTICATED_ANONYMOUSLY" security attribute is deprecated, use "PUBLIC_ACCESS" for public resources, otherwise use "IS_AUTHENTICATED" or "IS_AUTHENTICATED_FULLY" instead if you want to check if the request is (fully) authenticated.');
return VoterInterface::ACCESS_GRANTED;
}
// @deprecated $this->authenticationTrustResolver must implement isAuthenticated() in 6.0
if (self::IS_AUTHENTICATED === $attribute
&& (method_exists($this->authenticationTrustResolver, 'isAuthenticated')
? $this->authenticationTrustResolver->isAuthenticated($token)
: ($token && $token->getUser()))) {
return VoterInterface::ACCESS_GRANTED;
}
if (self::IS_REMEMBERED === $attribute && $this->authenticationTrustResolver->isRememberMe($token)) {
return VoterInterface::ACCESS_GRANTED;
}
if (self::IS_ANONYMOUS === $attribute && $this->authenticationTrustResolver->isAnonymous($token)) {
trigger_deprecation('symfony/security-core', '5.4', 'The "IS_ANONYMOUSLY" security attribute is deprecated, anonymous no longer exists in version 6.');
return VoterInterface::ACCESS_GRANTED;
}
if (self::IS_IMPERSONATOR === $attribute && $token instanceof SwitchUserToken) {
return VoterInterface::ACCESS_GRANTED;
}
}
return $result;
}
public function supportsAttribute(string $attribute): bool
{
return \in_array($attribute, [
self::IS_AUTHENTICATED_FULLY,
self::IS_AUTHENTICATED_REMEMBERED,
self::IS_AUTHENTICATED_ANONYMOUSLY,
self::IS_AUTHENTICATED,
self::IS_ANONYMOUS,
self::IS_IMPERSONATOR,
self::IS_REMEMBERED,
self::PUBLIC_ACCESS,
], true);
}
public function supportsType(string $subjectType): bool
{
return true;
}
}

View File

@ -0,0 +1,30 @@
<?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\Authorization\Voter;
/**
* Let voters expose the attributes and types they care about.
*
* By returning false to either `supportsAttribute` or `supportsType`, the
* voter will never be called for the specified attribute or subject.
*
* @author Jérémy Derussé <jeremy@derusse.com>
*/
interface CacheableVoterInterface extends VoterInterface
{
public function supportsAttribute(string $attribute): bool;
/**
* @param string $subjectType The type of the subject inferred by `get_class` or `get_debug_type`
*/
public function supportsType(string $subjectType): bool;
}

View File

@ -0,0 +1,104 @@
<?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\Authorization\Voter;
use Symfony\Component\ExpressionLanguage\Expression;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolverInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Authorization\ExpressionLanguage;
use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;
/**
* ExpressionVoter votes based on the evaluation of an expression.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class ExpressionVoter implements CacheableVoterInterface
{
private $expressionLanguage;
private $trustResolver;
private $authChecker;
private $roleHierarchy;
public function __construct(ExpressionLanguage $expressionLanguage, AuthenticationTrustResolverInterface $trustResolver, AuthorizationCheckerInterface $authChecker, RoleHierarchyInterface $roleHierarchy = null)
{
$this->expressionLanguage = $expressionLanguage;
$this->trustResolver = $trustResolver;
$this->authChecker = $authChecker;
$this->roleHierarchy = $roleHierarchy;
}
public function supportsAttribute(string $attribute): bool
{
return false;
}
public function supportsType(string $subjectType): bool
{
return true;
}
/**
* {@inheritdoc}
*/
public function vote(TokenInterface $token, $subject, array $attributes)
{
$result = VoterInterface::ACCESS_ABSTAIN;
$variables = null;
foreach ($attributes as $attribute) {
if (!$attribute instanceof Expression) {
continue;
}
if (null === $variables) {
$variables = $this->getVariables($token, $subject);
}
$result = VoterInterface::ACCESS_DENIED;
if ($this->expressionLanguage->evaluate($attribute, $variables)) {
return VoterInterface::ACCESS_GRANTED;
}
}
return $result;
}
private function getVariables(TokenInterface $token, $subject): array
{
$roleNames = $token->getRoleNames();
if (null !== $this->roleHierarchy) {
$roleNames = $this->roleHierarchy->getReachableRoleNames($roleNames);
}
$variables = [
'token' => $token,
'user' => $token->getUser(),
'object' => $subject,
'subject' => $subject,
'role_names' => $roleNames,
'trust_resolver' => $this->trustResolver,
'auth_checker' => $this->authChecker,
];
// this is mainly to propose a better experience when the expression is used
// in an access control rule, as the developer does not know that it's going
// to be handled by this voter
if ($subject instanceof Request) {
$variables['request'] = $subject;
}
return $variables;
}
}

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\Authorization\Voter;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;
/**
* RoleHierarchyVoter uses a RoleHierarchy to determine the roles granted to
* the user before voting.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class RoleHierarchyVoter extends RoleVoter
{
private $roleHierarchy;
public function __construct(RoleHierarchyInterface $roleHierarchy, string $prefix = 'ROLE_')
{
$this->roleHierarchy = $roleHierarchy;
parent::__construct($prefix);
}
/**
* {@inheritdoc}
*/
protected function extractRoles(TokenInterface $token)
{
return $this->roleHierarchy->getReachableRoleNames($token->getRoleNames());
}
}

View File

@ -0,0 +1,72 @@
<?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\Authorization\Voter;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
/**
* RoleVoter votes if any attribute starts with a given prefix.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class RoleVoter implements CacheableVoterInterface
{
private $prefix;
public function __construct(string $prefix = 'ROLE_')
{
$this->prefix = $prefix;
}
/**
* {@inheritdoc}
*/
public function vote(TokenInterface $token, $subject, array $attributes)
{
$result = VoterInterface::ACCESS_ABSTAIN;
$roles = $this->extractRoles($token);
foreach ($attributes as $attribute) {
if (!\is_string($attribute) || !str_starts_with($attribute, $this->prefix)) {
continue;
}
if ('ROLE_PREVIOUS_ADMIN' === $attribute) {
trigger_deprecation('symfony/security-core', '5.1', 'The ROLE_PREVIOUS_ADMIN role is deprecated and will be removed in version 6.0, use the IS_IMPERSONATOR attribute instead.');
}
$result = VoterInterface::ACCESS_DENIED;
foreach ($roles as $role) {
if ($attribute === $role) {
return VoterInterface::ACCESS_GRANTED;
}
}
}
return $result;
}
public function supportsAttribute(string $attribute): bool
{
return str_starts_with($attribute, $this->prefix);
}
public function supportsType(string $subjectType): bool
{
return true;
}
protected function extractRoles(TokenInterface $token)
{
return $token->getRoleNames();
}
}

View File

@ -0,0 +1,59 @@
<?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\Authorization\Voter;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Event\VoteEvent;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
/**
* Decorates voter classes to send result events.
*
* @author Laurent VOULLEMIER <laurent.voullemier@gmail.com>
*
* @internal
*/
class TraceableVoter implements CacheableVoterInterface
{
private $voter;
private $eventDispatcher;
public function __construct(VoterInterface $voter, EventDispatcherInterface $eventDispatcher)
{
$this->voter = $voter;
$this->eventDispatcher = $eventDispatcher;
}
public function vote(TokenInterface $token, $subject, array $attributes): int
{
$result = $this->voter->vote($token, $subject, $attributes);
$this->eventDispatcher->dispatch(new VoteEvent($this->voter, $subject, $attributes, $result), 'debug.security.authorization.vote');
return $result;
}
public function getDecoratedVoter(): VoterInterface
{
return $this->voter;
}
public function supportsAttribute(string $attribute): bool
{
return !$this->voter instanceof CacheableVoterInterface || $this->voter->supportsAttribute($attribute);
}
public function supportsType(string $subjectType): bool
{
return !$this->voter instanceof CacheableVoterInterface || $this->voter->supportsType($subjectType);
}
}

View File

@ -0,0 +1,101 @@
<?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\Authorization\Voter;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
/**
* Voter is an abstract default implementation of a voter.
*
* @author Roman Marintšenko <inoryy@gmail.com>
* @author Grégoire Pineau <lyrixx@lyrixx.info>
*/
abstract class Voter implements VoterInterface, CacheableVoterInterface
{
/**
* {@inheritdoc}
*/
public function vote(TokenInterface $token, $subject, array $attributes)
{
// abstain vote by default in case none of the attributes are supported
$vote = self::ACCESS_ABSTAIN;
foreach ($attributes as $attribute) {
try {
if (!$this->supports($attribute, $subject)) {
continue;
}
} catch (\TypeError $e) {
if (\PHP_VERSION_ID < 80000) {
if (0 === strpos($e->getMessage(), 'Argument 1 passed to')
&& false !== strpos($e->getMessage(), '::supports() must be of the type string')) {
continue;
}
} elseif (false !== strpos($e->getMessage(), 'supports(): Argument #1')) {
continue;
}
throw $e;
}
// as soon as at least one attribute is supported, default is to deny access
$vote = self::ACCESS_DENIED;
if ($this->voteOnAttribute($attribute, $subject, $token)) {
// grant access as soon as at least one attribute returns a positive response
return self::ACCESS_GRANTED;
}
}
return $vote;
}
/**
* Return false if your voter doesn't support the given attribute. Symfony will cache
* that decision and won't call your voter again for that attribute.
*/
public function supportsAttribute(string $attribute): bool
{
return true;
}
/**
* Return false if your voter doesn't support the given subject type. Symfony will cache
* that decision and won't call your voter again for that subject type.
*
* @param string $subjectType The type of the subject inferred by `get_class()` or `get_debug_type()`
*/
public function supportsType(string $subjectType): bool
{
return true;
}
/**
* Determines if the attribute and subject are supported by this voter.
*
* @param string $attribute An attribute
* @param mixed $subject The subject to secure, e.g. an object the user wants to access or any other PHP type
*
* @return bool
*/
abstract protected function supports(string $attribute, $subject);
/**
* Perform a single access check operation on a given attribute, subject and token.
* It is safe to assume that $attribute and $subject already passed the "supports()" method check.
*
* @param mixed $subject
*
* @return bool
*/
abstract protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token);
}

View File

@ -0,0 +1,39 @@
<?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\Authorization\Voter;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
/**
* VoterInterface is the interface implemented by all voters.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
interface VoterInterface
{
public const ACCESS_GRANTED = 1;
public const ACCESS_ABSTAIN = 0;
public const ACCESS_DENIED = -1;
/**
* Returns the vote for the given parameters.
*
* This method must return one of the following constants:
* ACCESS_GRANTED, ACCESS_DENIED, or ACCESS_ABSTAIN.
*
* @param mixed $subject The subject to secure
* @param array $attributes An array of attributes associated with the method being invoked
*
* @return int either ACCESS_GRANTED, ACCESS_ABSTAIN, or ACCESS_DENIED
*/
public function vote(TokenInterface $token, $subject, array $attributes);
}

View File

@ -0,0 +1,31 @@
CHANGELOG
=========
5.4
---
* Add a `CacheableVoterInterface` for voters that vote only on identified attributes and subjects
* Deprecate `AuthenticationEvents::AUTHENTICATION_FAILURE`, use the `LoginFailureEvent` instead
* Deprecate `AnonymousToken`, as the related authenticator was deprecated in 5.3
* Deprecate `Token::getCredentials()`, tokens should no longer contain credentials (as they represent authenticated sessions)
* Deprecate returning `string|\Stringable` from `Token::getUser()` (it must return a `UserInterface`)
* Deprecate `AuthenticatedVoter::IS_AUTHENTICATED_ANONYMOUSLY` and `AuthenticatedVoter::IS_ANONYMOUS`,
use `AuthenticatedVoter::IS_AUTHENTICATED_FULLY` or `AuthenticatedVoter::IS_AUTHENTICATED` instead.
* Deprecate `AuthenticationTrustResolverInterface::isAnonymous()` and the `is_anonymous()` expression
function as anonymous no longer exists in version 6, use the `isFullFledged()` or the new
`isAuthenticated()` instead if you want to check if the request is (fully) authenticated.
* Deprecate the `$authenticationManager` argument of the `AuthorizationChecker` constructor
* Deprecate setting the `$alwaysAuthenticate` argument to `true` and not setting the
`$exceptionOnNoToken` argument to `false` of `AuthorizationChecker`
* Deprecate methods `TokenInterface::isAuthenticated()` and `setAuthenticated`,
return null from "getUser()" instead when a token is not authenticated
* Add `AccessDecisionStrategyInterface` to allow custom access decision strategies
* Add access decision strategies `AffirmativeStrategy`, `ConsensusStrategy`, `PriorityStrategy`, `UnanimousStrategy`
* Deprecate passing the strategy as string to `AccessDecisionManager`,
pass an instance of `AccessDecisionStrategyInterface` instead
* Flag `AccessDecisionManager` as `@final`
5.3
---
The CHANGELOG for version 5.3 and earlier can be found at https://github.com/symfony/symfony/blob/5.3/src/Symfony/Component/Security/CHANGELOG.md

View File

@ -0,0 +1,102 @@
<?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\Encoder;
use Symfony\Component\PasswordHasher\Hasher\CheckPasswordLengthTrait;
trigger_deprecation('symfony/security-core', '5.3', 'The "%s" class is deprecated, use "%s" instead.', BasePasswordEncoder::class, CheckPasswordLengthTrait::class);
/**
* BasePasswordEncoder is the base class for all password encoders.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated since Symfony 5.3, use CheckPasswordLengthTrait instead
*/
abstract class BasePasswordEncoder implements PasswordEncoderInterface
{
public const MAX_PASSWORD_LENGTH = 4096;
/**
* {@inheritdoc}
*/
public function needsRehash(string $encoded): bool
{
return false;
}
/**
* Demerges a merge password and salt string.
*
* @return array An array where the first element is the password and the second the salt
*/
protected function demergePasswordAndSalt(string $mergedPasswordSalt)
{
if (empty($mergedPasswordSalt)) {
return ['', ''];
}
$password = $mergedPasswordSalt;
$salt = '';
$saltBegins = strrpos($mergedPasswordSalt, '{');
if (false !== $saltBegins && $saltBegins + 1 < \strlen($mergedPasswordSalt)) {
$salt = substr($mergedPasswordSalt, $saltBegins + 1, -1);
$password = substr($mergedPasswordSalt, 0, $saltBegins);
}
return [$password, $salt];
}
/**
* Merges a password and a salt.
*
* @return string
*
* @throws \InvalidArgumentException
*/
protected function mergePasswordAndSalt(string $password, ?string $salt)
{
if (empty($salt)) {
return $password;
}
if (false !== strrpos($salt, '{') || false !== strrpos($salt, '}')) {
throw new \InvalidArgumentException('Cannot use { or } in salt.');
}
return $password.'{'.$salt.'}';
}
/**
* Compares two passwords.
*
* This method implements a constant-time algorithm to compare passwords to
* avoid (remote) timing attacks.
*
* @return bool
*/
protected function comparePasswords(string $password1, string $password2)
{
return hash_equals($password1, $password2);
}
/**
* Checks if the password is too long.
*
* @return bool
*/
protected function isPasswordTooLong(string $password)
{
return \strlen($password) > static::MAX_PASSWORD_LENGTH;
}
}

View File

@ -0,0 +1,32 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Security\Core\Encoder;
use Symfony\Component\PasswordHasher\Hasher\PasswordHasherAwareInterface;
/**
* @author Christophe Coevoet <stof@notk.org>
*
* @deprecated since Symfony 5.3, use {@link PasswordHasherAwareInterface} instead.
*/
interface EncoderAwareInterface
{
/**
* Gets the name of the encoder used to encode the password.
*
* If the method returns null, the standard way to retrieve the encoder
* will be used instead.
*
* @return string|null
*/
public function getEncoderName();
}

View File

@ -0,0 +1,227 @@
<?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\Encoder;
use Symfony\Component\PasswordHasher\Hasher\PasswordHasherAwareInterface;
use Symfony\Component\PasswordHasher\Hasher\PasswordHasherFactory;
use Symfony\Component\PasswordHasher\LegacyPasswordHasherInterface;
use Symfony\Component\PasswordHasher\PasswordHasherInterface;
use Symfony\Component\Security\Core\Exception\LogicException;
trigger_deprecation('symfony/security-core', '5.3', 'The "%s" class is deprecated, use "%s" instead.', EncoderFactory::class, PasswordHasherFactory::class);
/**
* A generic encoder factory implementation.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*
* @deprecated since Symfony 5.3, use {@link PasswordHasherFactory} instead
*/
class EncoderFactory implements EncoderFactoryInterface
{
private $encoders;
public function __construct(array $encoders)
{
$this->encoders = $encoders;
}
/**
* {@inheritdoc}
*/
public function getEncoder($user)
{
$encoderKey = null;
if (($user instanceof PasswordHasherAwareInterface && null !== $encoderName = $user->getPasswordHasherName()) || ($user instanceof EncoderAwareInterface && null !== $encoderName = $user->getEncoderName())) {
if (!\array_key_exists($encoderName, $this->encoders)) {
throw new \RuntimeException(sprintf('The encoder "%s" was not configured.', $encoderName));
}
$encoderKey = $encoderName;
} else {
foreach ($this->encoders as $class => $encoder) {
if ((\is_object($user) && $user instanceof $class) || (!\is_object($user) && (is_subclass_of($user, $class) || $user == $class))) {
$encoderKey = $class;
break;
}
}
}
if (null === $encoderKey) {
throw new \RuntimeException(sprintf('No encoder has been configured for account "%s".', \is_object($user) ? get_debug_type($user) : $user));
}
if (!$this->encoders[$encoderKey] instanceof PasswordEncoderInterface) {
if ($this->encoders[$encoderKey] instanceof LegacyPasswordHasherInterface) {
$this->encoders[$encoderKey] = new LegacyPasswordHasherEncoder($this->encoders[$encoderKey]);
} elseif ($this->encoders[$encoderKey] instanceof PasswordHasherInterface) {
$this->encoders[$encoderKey] = new PasswordHasherEncoder($this->encoders[$encoderKey]);
} else {
$this->encoders[$encoderKey] = $this->createEncoder($this->encoders[$encoderKey]);
}
}
return $this->encoders[$encoderKey];
}
/**
* Creates the actual encoder instance.
*
* @throws \InvalidArgumentException
*/
private function createEncoder(array $config, bool $isExtra = false): PasswordEncoderInterface
{
if (isset($config['algorithm'])) {
$rawConfig = $config;
$config = $this->getEncoderConfigFromAlgorithm($config);
}
if (!isset($config['class'])) {
throw new \InvalidArgumentException('"class" must be set in '.json_encode($config));
}
if (!isset($config['arguments'])) {
throw new \InvalidArgumentException('"arguments" must be set in '.json_encode($config));
}
$encoder = new $config['class'](...$config['arguments']);
if ($isExtra || !\in_array($config['class'], [NativePasswordEncoder::class, SodiumPasswordEncoder::class], true)) {
return $encoder;
}
if ($rawConfig ?? null) {
$extraEncoders = array_map(function (string $algo) use ($rawConfig): PasswordEncoderInterface {
$rawConfig['algorithm'] = $algo;
return $this->createEncoder($rawConfig);
}, ['pbkdf2', $rawConfig['hash_algorithm'] ?? 'sha512']);
} else {
$extraEncoders = [new Pbkdf2PasswordEncoder(), new MessageDigestPasswordEncoder()];
}
return new MigratingPasswordEncoder($encoder, ...$extraEncoders);
}
private function getEncoderConfigFromAlgorithm(array $config): array
{
if ('auto' === $config['algorithm']) {
$encoderChain = [];
// "plaintext" is not listed as any leaked hashes could then be used to authenticate directly
foreach ([SodiumPasswordEncoder::isSupported() ? 'sodium' : 'native', 'pbkdf2', $config['hash_algorithm']] as $algo) {
$config['algorithm'] = $algo;
$encoderChain[] = $this->createEncoder($config, true);
}
return [
'class' => MigratingPasswordEncoder::class,
'arguments' => $encoderChain,
];
}
if ($fromEncoders = ($config['migrate_from'] ?? false)) {
unset($config['migrate_from']);
$encoderChain = [$this->createEncoder($config, true)];
foreach ($fromEncoders as $name) {
if ($encoder = $this->encoders[$name] ?? false) {
$encoder = $encoder instanceof PasswordEncoderInterface ? $encoder : $this->createEncoder($encoder, true);
} else {
$encoder = $this->createEncoder(['algorithm' => $name], true);
}
$encoderChain[] = $encoder;
}
return [
'class' => MigratingPasswordEncoder::class,
'arguments' => $encoderChain,
];
}
switch ($config['algorithm']) {
case 'plaintext':
return [
'class' => PlaintextPasswordEncoder::class,
'arguments' => [$config['ignore_case']],
];
case 'pbkdf2':
return [
'class' => Pbkdf2PasswordEncoder::class,
'arguments' => [
$config['hash_algorithm'] ?? 'sha512',
$config['encode_as_base64'] ?? true,
$config['iterations'] ?? 1000,
$config['key_length'] ?? 40,
],
];
case 'bcrypt':
$config['algorithm'] = 'native';
$config['native_algorithm'] = \PASSWORD_BCRYPT;
return $this->getEncoderConfigFromAlgorithm($config);
case 'native':
return [
'class' => NativePasswordEncoder::class,
'arguments' => [
$config['time_cost'] ?? null,
(($config['memory_cost'] ?? 0) << 10) ?: null,
$config['cost'] ?? null,
] + (isset($config['native_algorithm']) ? [3 => $config['native_algorithm']] : []),
];
case 'sodium':
return [
'class' => SodiumPasswordEncoder::class,
'arguments' => [
$config['time_cost'] ?? null,
(($config['memory_cost'] ?? 0) << 10) ?: null,
],
];
case 'argon2i':
if (SodiumPasswordEncoder::isSupported() && !\defined('SODIUM_CRYPTO_PWHASH_ALG_ARGON2ID13')) {
$config['algorithm'] = 'sodium';
} elseif (\defined('PASSWORD_ARGON2I')) {
$config['algorithm'] = 'native';
$config['native_algorithm'] = \PASSWORD_ARGON2I;
} else {
throw new LogicException(sprintf('Algorithm "argon2i" is not available. Either use %s"auto" or upgrade to PHP 7.2+ instead.', \defined('SODIUM_CRYPTO_PWHASH_ALG_ARGON2ID13') ? '"argon2id", ' : ''));
}
return $this->getEncoderConfigFromAlgorithm($config);
case 'argon2id':
if (($hasSodium = SodiumPasswordEncoder::isSupported()) && \defined('SODIUM_CRYPTO_PWHASH_ALG_ARGON2ID13')) {
$config['algorithm'] = 'sodium';
} elseif (\defined('PASSWORD_ARGON2ID')) {
$config['algorithm'] = 'native';
$config['native_algorithm'] = \PASSWORD_ARGON2ID;
} else {
throw new LogicException(sprintf('Algorithm "argon2id" is not available. Either use %s"auto", upgrade to PHP 7.3+ or use libsodium 1.0.15+ instead.', \defined('PASSWORD_ARGON2I') || $hasSodium ? '"argon2i", ' : ''));
}
return $this->getEncoderConfigFromAlgorithm($config);
}
return [
'class' => MessageDigestPasswordEncoder::class,
'arguments' => [
$config['algorithm'],
$config['encode_as_base64'] ?? true,
$config['iterations'] ?? 5000,
],
];
}
}

View File

@ -0,0 +1,38 @@
<?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\Encoder;
use Symfony\Component\PasswordHasher\Hasher\PasswordHasherFactoryInterface;
use Symfony\Component\Security\Core\User\UserInterface;
trigger_deprecation('symfony/security-core', '5.3', 'The "%s" class is deprecated, use "%s" instead.', EncoderFactoryInterface::class, PasswordHasherFactoryInterface::class);
/**
* EncoderFactoryInterface to support different encoders for different accounts.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*
* @deprecated since Symfony 5.3, use {@link PasswordHasherFactoryInterface} instead
*/
interface EncoderFactoryInterface
{
/**
* Returns the password encoder to use for the given account.
*
* @param UserInterface|string $user A UserInterface instance or a class name
*
* @return PasswordEncoderInterface
*
* @throws \RuntimeException when no password encoder could be found for the user
*/
public function getEncoder($user);
}

View File

@ -0,0 +1,56 @@
<?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\Encoder;
use Symfony\Component\PasswordHasher\Exception\InvalidPasswordException;
use Symfony\Component\PasswordHasher\LegacyPasswordHasherInterface;
use Symfony\Component\PasswordHasher\PasswordHasherInterface;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
/**
* @internal
*/
trait LegacyEncoderTrait
{
/**
* @var PasswordHasherInterface|LegacyPasswordHasherInterface
*/
private $hasher;
/**
* {@inheritdoc}
*/
public function encodePassword(string $raw, ?string $salt): string
{
try {
return $this->hasher->hash($raw, $salt);
} catch (InvalidPasswordException $e) {
throw new BadCredentialsException('Bad credentials.');
}
}
/**
* {@inheritdoc}
*/
public function isPasswordValid(string $encoded, string $raw, ?string $salt): bool
{
return $this->hasher->verify($encoded, $raw, $salt);
}
/**
* {@inheritdoc}
*/
public function needsRehash(string $encoded): bool
{
return $this->hasher->needsRehash($encoded);
}
}

View File

@ -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\Component\Security\Core\Encoder;
use Symfony\Component\PasswordHasher\Exception\InvalidPasswordException;
use Symfony\Component\PasswordHasher\LegacyPasswordHasherInterface;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
/**
* Forward compatibility for new new PasswordHasher component.
*
* @author Alexander M. Turek <me@derrabus.de>
*
* @internal To be removed in Symfony 6
*/
final class LegacyPasswordHasherEncoder implements PasswordEncoderInterface
{
private $passwordHasher;
public function __construct(LegacyPasswordHasherInterface $passwordHasher)
{
$this->passwordHasher = $passwordHasher;
}
public function encodePassword(string $raw, ?string $salt): string
{
try {
return $this->passwordHasher->hash($raw, $salt);
} catch (InvalidPasswordException $e) {
throw new BadCredentialsException($e->getMessage(), $e->getCode(), $e);
}
}
public function isPasswordValid(string $encoded, string $raw, ?string $salt): bool
{
return $this->passwordHasher->verify($encoded, $raw, $salt);
}
public function needsRehash(string $encoded): bool
{
return $this->passwordHasher->needsRehash($encoded);
}
}

View File

@ -0,0 +1,87 @@
<?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\Encoder;
use Symfony\Component\PasswordHasher\Hasher\MessageDigestPasswordHasher;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
trigger_deprecation('symfony/security-core', '5.3', 'The "%s" class is deprecated, use "%s" instead.', MessageDigestPasswordEncoder::class, MessageDigestPasswordHasher::class);
/**
* MessageDigestPasswordEncoder uses a message digest algorithm.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated since Symfony 5.3, use {@link MessageDigestPasswordHasher} instead
*/
class MessageDigestPasswordEncoder extends BasePasswordEncoder
{
private $algorithm;
private $encodeHashAsBase64;
private $iterations = 1;
private $encodedLength = -1;
/**
* @param string $algorithm The digest algorithm to use
* @param bool $encodeHashAsBase64 Whether to base64 encode the password hash
* @param int $iterations The number of iterations to use to stretch the password hash
*/
public function __construct(string $algorithm = 'sha512', bool $encodeHashAsBase64 = true, int $iterations = 5000)
{
$this->algorithm = $algorithm;
$this->encodeHashAsBase64 = $encodeHashAsBase64;
try {
$this->encodedLength = \strlen($this->encodePassword('', 'salt'));
} catch (\LogicException $e) {
// ignore algorithm not supported
}
$this->iterations = $iterations;
}
/**
* {@inheritdoc}
*/
public function encodePassword(string $raw, ?string $salt)
{
if ($this->isPasswordTooLong($raw)) {
throw new BadCredentialsException('Invalid password.');
}
if (!\in_array($this->algorithm, hash_algos(), true)) {
throw new \LogicException(sprintf('The algorithm "%s" is not supported.', $this->algorithm));
}
$salted = $this->mergePasswordAndSalt($raw, $salt);
$digest = hash($this->algorithm, $salted, true);
// "stretch" hash
for ($i = 1; $i < $this->iterations; ++$i) {
$digest = hash($this->algorithm, $digest.$salted, true);
}
return $this->encodeHashAsBase64 ? base64_encode($digest) : bin2hex($digest);
}
/**
* {@inheritdoc}
*/
public function isPasswordValid(string $encoded, string $raw, ?string $salt)
{
if (\strlen($encoded) !== $this->encodedLength || str_contains($encoded, '$')) {
return false;
}
return !$this->isPasswordTooLong($raw) && $this->comparePasswords($encoded, $this->encodePassword($raw, $salt));
}
}

View File

@ -0,0 +1,77 @@
<?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\Encoder;
use Symfony\Component\PasswordHasher\Hasher\MigratingPasswordHasher;
trigger_deprecation('symfony/security-core', '5.3', 'The "%s" class is deprecated, use "%s" instead.', MigratingPasswordEncoder::class, MigratingPasswordHasher::class);
/**
* Hashes passwords using the best available encoder.
* Validates them using a chain of encoders.
*
* /!\ Don't put a PlaintextPasswordEncoder in the list as that'd mean a leaked hash
* could be used to authenticate successfully without knowing the cleartext password.
*
* @author Nicolas Grekas <p@tchwork.com>
*
* @deprecated since Symfony 5.3, use {@link MigratingPasswordHasher} instead
*/
final class MigratingPasswordEncoder extends BasePasswordEncoder implements SelfSaltingEncoderInterface
{
private $bestEncoder;
private $extraEncoders;
public function __construct(PasswordEncoderInterface $bestEncoder, PasswordEncoderInterface ...$extraEncoders)
{
$this->bestEncoder = $bestEncoder;
$this->extraEncoders = $extraEncoders;
}
/**
* {@inheritdoc}
*/
public function encodePassword(string $raw, ?string $salt): string
{
return $this->bestEncoder->encodePassword($raw, $salt);
}
/**
* {@inheritdoc}
*/
public function isPasswordValid(string $encoded, string $raw, ?string $salt): bool
{
if ($this->bestEncoder->isPasswordValid($encoded, $raw, $salt)) {
return true;
}
if (!$this->bestEncoder->needsRehash($encoded)) {
return false;
}
foreach ($this->extraEncoders as $encoder) {
if ($encoder->isPasswordValid($encoded, $raw, $salt)) {
return true;
}
}
return false;
}
/**
* {@inheritdoc}
*/
public function needsRehash(string $encoded): bool
{
return $this->bestEncoder->needsRehash($encoded);
}
}

View File

@ -0,0 +1,38 @@
<?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\Encoder;
use Symfony\Component\PasswordHasher\Hasher\NativePasswordHasher;
trigger_deprecation('symfony/security-core', '5.3', 'The "%s" class is deprecated, use "%s" instead.', NativePasswordEncoder::class, NativePasswordHasher::class);
/**
* Hashes passwords using password_hash().
*
* @author Elnur Abdurrakhimov <elnur@elnur.pro>
* @author Terje Bråten <terje@braten.be>
* @author Nicolas Grekas <p@tchwork.com>
*
* @deprecated since Symfony 5.3, use {@link NativePasswordHasher} instead
*/
final class NativePasswordEncoder implements PasswordEncoderInterface, SelfSaltingEncoderInterface
{
use LegacyEncoderTrait;
/**
* @param string|null $algo An algorithm supported by password_hash() or null to use the stronger available algorithm
*/
public function __construct(int $opsLimit = null, int $memLimit = null, int $cost = null, string $algo = null)
{
$this->hasher = new NativePasswordHasher($opsLimit, $memLimit, $cost, $algo);
}
}

View File

@ -0,0 +1,55 @@
<?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\Encoder;
use Symfony\Component\PasswordHasher\PasswordHasherInterface;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
trigger_deprecation('symfony/security-core', '5.3', 'The "%s" class is deprecated, use "%s" instead.', PasswordEncoderInterface::class, PasswordHasherInterface::class);
/**
* PasswordEncoderInterface is the interface for all encoders.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated since Symfony 5.3, use {@link PasswordHasherInterface} instead
*/
interface PasswordEncoderInterface
{
/**
* Encodes the raw password.
*
* @return string
*
* @throws BadCredentialsException If the raw password is invalid, e.g. excessively long
* @throws \InvalidArgumentException If the salt is invalid
*/
public function encodePassword(string $raw, ?string $salt);
/**
* Checks a raw password against an encoded password.
*
* @param string $encoded An encoded password
* @param string $raw A raw password
* @param string|null $salt The salt
*
* @return bool
*
* @throws \InvalidArgumentException If the salt is invalid
*/
public function isPasswordValid(string $encoded, string $raw, ?string $salt);
/**
* Checks if an encoded password would benefit from rehashing.
*/
public function needsRehash(string $encoded): bool;
}

View File

@ -0,0 +1,46 @@
<?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\Encoder;
use Symfony\Component\PasswordHasher\LegacyPasswordHasherInterface;
/**
* Forward compatibility for new new PasswordHasher component.
*
* @author Alexander M. Turek <me@derrabus.de>
*
* @internal To be removed in Symfony 6
*/
final class PasswordHasherAdapter implements LegacyPasswordHasherInterface
{
private $passwordEncoder;
public function __construct(PasswordEncoderInterface $passwordEncoder)
{
$this->passwordEncoder = $passwordEncoder;
}
public function hash(string $plainPassword, string $salt = null): string
{
return $this->passwordEncoder->encodePassword($plainPassword, $salt);
}
public function verify(string $hashedPassword, string $plainPassword, string $salt = null): bool
{
return $this->passwordEncoder->isPasswordValid($hashedPassword, $plainPassword, $salt);
}
public function needsRehash(string $hashedPassword): bool
{
return $this->passwordEncoder->needsRehash($hashedPassword);
}
}

View File

@ -0,0 +1,60 @@
<?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\Encoder;
use Symfony\Component\PasswordHasher\Exception\InvalidPasswordException;
use Symfony\Component\PasswordHasher\PasswordHasherInterface;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
/**
* Forward compatibility for new new PasswordHasher component.
*
* @author Alexander M. Turek <me@derrabus.de>
*
* @internal To be removed in Symfony 6
*/
final class PasswordHasherEncoder implements PasswordEncoderInterface, SelfSaltingEncoderInterface
{
private $passwordHasher;
public function __construct(PasswordHasherInterface $passwordHasher)
{
$this->passwordHasher = $passwordHasher;
}
public function encodePassword(string $raw, ?string $salt): string
{
if (null !== $salt) {
throw new \InvalidArgumentException('This password hasher does not support passing a salt.');
}
try {
return $this->passwordHasher->hash($raw);
} catch (InvalidPasswordException $e) {
throw new BadCredentialsException($e->getMessage(), $e->getCode(), $e);
}
}
public function isPasswordValid(string $encoded, string $raw, ?string $salt): bool
{
if (null !== $salt) {
throw new \InvalidArgumentException('This password hasher does not support passing a salt.');
}
return $this->passwordHasher->verify($encoded, $raw);
}
public function needsRehash(string $encoded): bool
{
return $this->passwordHasher->needsRehash($encoded);
}
}

View File

@ -0,0 +1,47 @@
<?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\Encoder;
use Symfony\Component\PasswordHasher\Hasher\Pbkdf2PasswordHasher;
trigger_deprecation('symfony/security-core', '5.3', 'The "%s" class is deprecated, use "%s" instead.', Pbkdf2PasswordEncoder::class, Pbkdf2PasswordHasher::class);
/**
* Pbkdf2PasswordEncoder uses the PBKDF2 (Password-Based Key Derivation Function 2).
*
* Providing a high level of Cryptographic security,
* PBKDF2 is recommended by the National Institute of Standards and Technology (NIST).
*
* But also warrants a warning, using PBKDF2 (with a high number of iterations) slows down the process.
* PBKDF2 should be used with caution and care.
*
* @author Sebastiaan Stok <s.stok@rollerscapes.net>
* @author Andrew Johnson
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated since Symfony 5.3, use {@link Pbkdf2PasswordHasher} instead
*/
class Pbkdf2PasswordEncoder extends BasePasswordEncoder
{
use LegacyEncoderTrait;
/**
* @param string $algorithm The digest algorithm to use
* @param bool $encodeHashAsBase64 Whether to base64 encode the password hash
* @param int $iterations The number of iterations to use to stretch the password hash
* @param int $length Length of derived key to create
*/
public function __construct(string $algorithm = 'sha512', bool $encodeHashAsBase64 = true, int $iterations = 1000, int $length = 40)
{
$this->hasher = new Pbkdf2PasswordHasher($algorithm, $encodeHashAsBase64, $iterations, $length);
}
}

View File

@ -0,0 +1,38 @@
<?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\Encoder;
use Symfony\Component\PasswordHasher\Hasher\PlaintextPasswordHasher;
trigger_deprecation('symfony/security-core', '5.3', 'The "%s" class is deprecated, use "%s" instead.', PlaintextPasswordEncoder::class, PlaintextPasswordHasher::class);
/**
* PlaintextPasswordEncoder does not do any encoding but is useful in testing environments.
*
* As this encoder is not cryptographically secure, usage of it in production environments is discouraged.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated since Symfony 5.3, use {@link PlaintextPasswordHasher} instead
*/
class PlaintextPasswordEncoder extends BasePasswordEncoder
{
use LegacyEncoderTrait;
/**
* @param bool $ignorePasswordCase Compare password case-insensitive
*/
public function __construct(bool $ignorePasswordCase = false)
{
$this->hasher = new PlaintextPasswordHasher($ignorePasswordCase);
}
}

View File

@ -0,0 +1,28 @@
<?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\Encoder;
use Symfony\Component\PasswordHasher\LegacyPasswordHasherInterface;
trigger_deprecation('symfony/security-core', '5.3', 'The "%s" interface is deprecated, use "%s" on hasher implementations that deal with salts instead.', SelfSaltingEncoderInterface::class, LegacyPasswordHasherInterface::class);
/**
* SelfSaltingEncoderInterface is a marker interface for encoders that do not
* require a user-generated salt.
*
* @author Zan Baldwin <hello@zanbaldwin.com>
*
* @deprecated since Symfony 5.3, use {@link LegacyPasswordHasherInterface} instead
*/
interface SelfSaltingEncoderInterface
{
}

View File

@ -0,0 +1,40 @@
<?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\Encoder;
use Symfony\Component\PasswordHasher\Hasher\SodiumPasswordHasher;
trigger_deprecation('symfony/security-core', '5.3', 'The "%s" class is deprecated, use "%s" instead.', SodiumPasswordEncoder::class, SodiumPasswordHasher::class);
/**
* Hashes passwords using libsodium.
*
* @author Robin Chalas <robin.chalas@gmail.com>
* @author Zan Baldwin <hello@zanbaldwin.com>
* @author Dominik Müller <dominik.mueller@jkweb.ch>
*
* @deprecated since Symfony 5.3, use {@link SodiumPasswordHasher} instead
*/
final class SodiumPasswordEncoder implements PasswordEncoderInterface, SelfSaltingEncoderInterface
{
use LegacyEncoderTrait;
public function __construct(int $opsLimit = null, int $memLimit = null)
{
$this->hasher = new SodiumPasswordHasher($opsLimit, $memLimit);
}
public static function isSupported(): bool
{
return SodiumPasswordHasher::isSupported();
}
}

View File

@ -0,0 +1,83 @@
<?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\Encoder;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasher;
use Symfony\Component\Security\Core\User\LegacyPasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;
trigger_deprecation('symfony/security-core', '5.3', 'The "%s" class is deprecated, use "%s" instead.', UserPasswordEncoder::class, UserPasswordHasher::class);
/**
* A generic password encoder.
*
* @author Ariel Ferrandini <arielferrandini@gmail.com>
*
* @deprecated since Symfony 5.3, use {@link UserPasswordHasher} instead
*/
class UserPasswordEncoder implements UserPasswordEncoderInterface
{
private $encoderFactory;
public function __construct(EncoderFactoryInterface $encoderFactory)
{
$this->encoderFactory = $encoderFactory;
}
/**
* {@inheritdoc}
*/
public function encodePassword(UserInterface $user, string $plainPassword)
{
$encoder = $this->encoderFactory->getEncoder($user);
if (!$user instanceof PasswordAuthenticatedUserInterface) {
trigger_deprecation('symfony/password-hasher', '5.3', 'Not implementing the "%s" interface while using "%s" is deprecated, the "%s" class should implement it.', PasswordAuthenticatedUserInterface::class, __CLASS__, get_debug_type($user));
}
$salt = $user->getSalt();
if ($salt && !$user instanceof LegacyPasswordAuthenticatedUserInterface) {
trigger_deprecation('symfony/password-hasher', '5.3', 'Returning a string from "getSalt()" without implementing the "%s" interface is deprecated, the "%s" class should implement it.', LegacyPasswordAuthenticatedUserInterface::class, get_debug_type($user));
}
return $encoder->encodePassword($plainPassword, $user->getSalt());
}
/**
* {@inheritdoc}
*/
public function isPasswordValid(UserInterface $user, string $raw)
{
if (null === $user->getPassword()) {
return false;
}
$encoder = $this->encoderFactory->getEncoder($user);
return $encoder->isPasswordValid($user->getPassword(), $raw, $user->getSalt());
}
/**
* {@inheritdoc}
*/
public function needsRehash(UserInterface $user): bool
{
if (null === $user->getPassword()) {
return false;
}
$encoder = $this->encoderFactory->getEncoder($user);
return $encoder->needsRehash($user->getPassword());
}
}

View File

@ -0,0 +1,44 @@
<?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\Encoder;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Security\Core\User\UserInterface;
trigger_deprecation('symfony/security-core', '5.3', 'The "%s" interface is deprecated, use "%s" instead.', UserPasswordEncoderInterface::class, UserPasswordHasherInterface::class);
/**
* UserPasswordEncoderInterface is the interface for the password encoder service.
*
* @author Ariel Ferrandini <arielferrandini@gmail.com>
*
* @deprecated since Symfony 5.3, use {@link UserPasswordHasherInterface} instead
*/
interface UserPasswordEncoderInterface
{
/**
* Encodes the plain password.
*
* @return string
*/
public function encodePassword(UserInterface $user, string $plainPassword);
/**
* @return bool
*/
public function isPasswordValid(UserInterface $user, string $raw);
/**
* Checks if an encoded password would benefit from rehashing.
*/
public function needsRehash(UserInterface $user): bool;
}

View File

@ -0,0 +1,35 @@
<?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\Event;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Contracts\EventDispatcher\Event;
/**
* This is a general purpose authentication event.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
class AuthenticationEvent extends Event
{
private $authenticationToken;
public function __construct(TokenInterface $token)
{
$this->authenticationToken = $token;
}
public function getAuthenticationToken()
{
return $this->authenticationToken;
}
}

View File

@ -0,0 +1,42 @@
<?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\Event;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\Event\LoginFailureEvent;
trigger_deprecation('symfony/security-core', '5.3', 'The "%s" class is deprecated, use "%s" with the new authenticator system instead.', AuthenticationFailureEvent::class, LoginFailureEvent::class);
/**
* This event is dispatched on authentication failure.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*
* @deprecated since Symfony 5.3, use LoginFailureEvent with the new authenticator system instead
*/
final class AuthenticationFailureEvent extends AuthenticationEvent
{
private $authenticationException;
public function __construct(TokenInterface $token, AuthenticationException $ex)
{
parent::__construct($token);
$this->authenticationException = $ex;
}
public function getAuthenticationException(): AuthenticationException
{
return $this->authenticationException;
}
}

View File

@ -0,0 +1,16 @@
<?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\Event;
final class AuthenticationSuccessEvent extends AuthenticationEvent
{
}

View File

@ -0,0 +1,58 @@
<?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\Event;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
use Symfony\Contracts\EventDispatcher\Event;
/**
* This event is dispatched on voter vote.
*
* @author Laurent VOULLEMIER <laurent.voullemier@gmail.com>
*
* @internal
*/
final class VoteEvent extends Event
{
private $voter;
private $subject;
private $attributes;
private $vote;
public function __construct(VoterInterface $voter, $subject, array $attributes, int $vote)
{
$this->voter = $voter;
$this->subject = $subject;
$this->attributes = $attributes;
$this->vote = $vote;
}
public function getVoter(): VoterInterface
{
return $this->voter;
}
public function getSubject()
{
return $this->subject;
}
public function getAttributes(): array
{
return $this->attributes;
}
public function getVote(): int
{
return $this->vote;
}
}

View File

@ -0,0 +1,60 @@
<?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\Exception;
/**
* AccessDeniedException is thrown when the account has not the required role.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class AccessDeniedException extends RuntimeException
{
private $attributes = [];
private $subject;
public function __construct(string $message = 'Access Denied.', \Throwable $previous = null)
{
parent::__construct($message, 403, $previous);
}
/**
* @return array
*/
public function getAttributes()
{
return $this->attributes;
}
/**
* @param array|string $attributes
*/
public function setAttributes($attributes)
{
$this->attributes = (array) $attributes;
}
/**
* @return mixed
*/
public function getSubject()
{
return $this->subject;
}
/**
* @param mixed $subject
*/
public function setSubject($subject)
{
$this->subject = $subject;
}
}

View File

@ -0,0 +1,29 @@
<?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\Exception;
/**
* AccountExpiredException is thrown when the user account has expired.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Alexander <iam.asm89@gmail.com>
*/
class AccountExpiredException extends AccountStatusException
{
/**
* {@inheritdoc}
*/
public function getMessageKey()
{
return 'Account has expired.';
}
}

View File

@ -0,0 +1,59 @@
<?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\Exception;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* AccountStatusException is the base class for authentication exceptions
* caused by the user account status.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Alexander <iam.asm89@gmail.com>
*/
abstract class AccountStatusException extends AuthenticationException
{
private $user;
/**
* Get the user.
*
* @return UserInterface|null
*/
public function getUser()
{
return $this->user;
}
public function setUser(UserInterface $user)
{
$this->user = $user;
}
/**
* {@inheritdoc}
*/
public function __serialize(): array
{
return [$this->user, parent::__serialize()];
}
/**
* {@inheritdoc}
*/
public function __unserialize(array $data): void
{
[$this->user, $parentData] = $data;
$parentData = \is_array($parentData) ? $parentData : unserialize($parentData);
parent::__unserialize($parentData);
}
}

View File

@ -0,0 +1,30 @@
<?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\Exception;
/**
* AuthenticationCredentialsNotFoundException is thrown when an authentication is rejected
* because no Token is available.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Alexander <iam.asm89@gmail.com>
*/
class AuthenticationCredentialsNotFoundException extends AuthenticationException
{
/**
* {@inheritdoc}
*/
public function getMessageKey()
{
return 'Authentication credentials could not be found.';
}
}

View File

@ -0,0 +1,127 @@
<?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\Exception;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
/**
* AuthenticationException is the base class for all authentication exceptions.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Alexander <iam.asm89@gmail.com>
*/
class AuthenticationException extends RuntimeException
{
/** @internal */
protected $serialized;
private $token;
public function __construct(string $message = '', int $code = 0, \Throwable $previous = null)
{
unset($this->serialized);
parent::__construct($message, $code, $previous);
}
/**
* @return TokenInterface|null
*/
public function getToken()
{
return $this->token;
}
public function setToken(TokenInterface $token)
{
$this->token = $token;
}
/**
* Returns all the necessary state of the object for serialization purposes.
*
* There is no need to serialize any entry, they should be returned as-is.
* If you extend this method, keep in mind you MUST guarantee parent data is present in the state.
* Here is an example of how to extend this method:
* <code>
* public function __serialize(): array
* {
* return [$this->childAttribute, parent::__serialize()];
* }
* </code>
*
* @see __unserialize()
*/
public function __serialize(): array
{
return [$this->token, $this->code, $this->message, $this->file, $this->line];
}
/**
* Restores the object state from an array given by __serialize().
*
* There is no need to unserialize any entry in $data, they are already ready-to-use.
* If you extend this method, keep in mind you MUST pass the parent data to its respective class.
* Here is an example of how to extend this method:
* <code>
* public function __unserialize(array $data): void
* {
* [$this->childAttribute, $parentData] = $data;
* parent::__unserialize($parentData);
* }
* </code>
*
* @see __serialize()
*/
public function __unserialize(array $data): void
{
[$this->token, $this->code, $this->message, $this->file, $this->line] = $data;
}
/**
* Message key to be used by the translation component.
*
* @return string
*/
public function getMessageKey()
{
return 'An authentication exception occurred.';
}
/**
* Message data to be used by the translation component.
*
* @return array
*/
public function getMessageData()
{
return [];
}
/**
* @internal
*/
public function __sleep(): array
{
$this->serialized = $this->__serialize();
return ['serialized'];
}
/**
* @internal
*/
public function __wakeup(): void
{
$this->__unserialize($this->serialized);
unset($this->serialized);
}
}

View File

@ -0,0 +1,31 @@
<?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\Exception;
/**
* AuthenticationExpiredException is thrown when an authentication token becomes un-authenticated between requests.
*
* In practice, this is due to the User changing between requests (e.g. password changes),
* causes the token to become un-authenticated.
*
* @author Ryan Weaver <ryan@knpuniversity.com>
*/
class AuthenticationExpiredException extends AccountStatusException
{
/**
* {@inheritdoc}
*/
public function getMessageKey()
{
return 'Authentication expired because your account information has changed.';
}
}

View File

@ -0,0 +1,29 @@
<?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\Exception;
/**
* AuthenticationServiceException is thrown when an authentication request could not be processed due to a system problem.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Alexander <iam.asm89@gmail.com>
*/
class AuthenticationServiceException extends AuthenticationException
{
/**
* {@inheritdoc}
*/
public function getMessageKey()
{
return 'Authentication request could not be processed due to a system problem.';
}
}

View File

@ -0,0 +1,29 @@
<?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\Exception;
/**
* BadCredentialsException is thrown when the user credentials are invalid.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Alexander <iam.asm89@gmail.com>
*/
class BadCredentialsException extends AuthenticationException
{
/**
* {@inheritdoc}
*/
public function getMessageKey()
{
return 'Invalid credentials.';
}
}

View File

@ -0,0 +1,30 @@
<?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\Exception;
/**
* This exception is thrown when the RememberMeServices implementation
* detects that a presented cookie has already been used by someone else.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
* @author Alexander <iam.asm89@gmail.com>
*/
class CookieTheftException extends AuthenticationException
{
/**
* {@inheritdoc}
*/
public function getMessageKey()
{
return 'Cookie has already been used by someone else.';
}
}

View File

@ -0,0 +1,29 @@
<?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\Exception;
/**
* CredentialsExpiredException is thrown when the user account credentials have expired.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Alexander <iam.asm89@gmail.com>
*/
class CredentialsExpiredException extends AccountStatusException
{
/**
* {@inheritdoc}
*/
public function getMessageKey()
{
return 'Credentials have expired.';
}
}

View File

@ -0,0 +1,75 @@
<?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\Exception;
/**
* An authentication exception caused by the user account status
* where you can control the message shown to the user.
*
* Be sure that the message passed to this exception is something that
* can be shown safely to your user. In other words, avoid catching
* other exceptions and passing their message directly to this class.
*
* @author Vincent Langlet <vincentlanglet@github.com>
*/
class CustomUserMessageAccountStatusException extends AccountStatusException
{
private $messageKey;
private $messageData = [];
public function __construct(string $message = '', array $messageData = [], int $code = 0, \Throwable $previous = null)
{
parent::__construct($message, $code, $previous);
$this->setSafeMessage($message, $messageData);
}
/**
* Sets a message that will be shown to the user.
*
* @param string $messageKey The message or message key
* @param array $messageData Data to be passed into the translator
*/
public function setSafeMessage(string $messageKey, array $messageData = [])
{
$this->messageKey = $messageKey;
$this->messageData = $messageData;
}
public function getMessageKey()
{
return $this->messageKey;
}
public function getMessageData()
{
return $this->messageData;
}
/**
* {@inheritdoc}
*/
public function __serialize(): array
{
return [parent::__serialize(), $this->messageKey, $this->messageData];
}
/**
* {@inheritdoc}
*/
public function __unserialize(array $data): void
{
[$parentData, $this->messageKey, $this->messageData] = $data;
parent::__unserialize($parentData);
}
}

View File

@ -0,0 +1,75 @@
<?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\Exception;
/**
* An authentication exception where you can control the message shown to the user.
*
* Be sure that the message passed to this exception is something that
* can be shown safely to your user. In other words, avoid catching
* other exceptions and passing their message directly to this class.
*
* @author Ryan Weaver <ryan@knpuniversity.com>
*/
class CustomUserMessageAuthenticationException extends AuthenticationException
{
private $messageKey;
private $messageData = [];
public function __construct(string $message = '', array $messageData = [], int $code = 0, \Throwable $previous = null)
{
parent::__construct($message, $code, $previous);
$this->setSafeMessage($message, $messageData);
}
/**
* Set a message that will be shown to the user.
*
* @param string $messageKey The message or message key
* @param array $messageData Data to be passed into the translator
*/
public function setSafeMessage(string $messageKey, array $messageData = [])
{
$this->messageKey = $messageKey;
$this->messageData = $messageData;
}
public function getMessageKey()
{
return $this->messageKey;
}
public function getMessageData()
{
return $this->messageData;
}
/**
* {@inheritdoc}
*/
public function __serialize(): array
{
return [parent::__serialize(), $this->messageKey, $this->messageData];
}
/**
* {@inheritdoc}
*/
public function __unserialize(array $data): void
{
[$parentData, $this->messageKey, $this->messageData] = $data;
$parentData = \is_array($parentData) ? $parentData : unserialize($parentData);
parent::__unserialize($parentData);
}
}

View File

@ -0,0 +1,29 @@
<?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\Exception;
/**
* DisabledException is thrown when the user account is disabled.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Alexander <iam.asm89@gmail.com>
*/
class DisabledException extends AccountStatusException
{
/**
* {@inheritdoc}
*/
public function getMessageKey()
{
return 'Account is disabled.';
}
}

View File

@ -0,0 +1,21 @@
<?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\Exception;
/**
* Base ExceptionInterface for the Security component.
*
* @author Bernhard Schussek <bschussek@gmail.com>
*/
interface ExceptionInterface extends \Throwable
{
}

View File

@ -0,0 +1,31 @@
<?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\Exception;
/**
* InsufficientAuthenticationException is thrown if the user credentials are not sufficiently trusted.
*
* This is the case when a user is anonymous and the resource to be displayed has an access role.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Alexander <iam.asm89@gmail.com>
*/
class InsufficientAuthenticationException extends AuthenticationException
{
/**
* {@inheritdoc}
*/
public function getMessageKey()
{
return 'Not privileged to request the resource.';
}
}

View File

@ -0,0 +1,21 @@
<?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\Exception;
/**
* Base InvalidArgumentException for the Security component.
*
* @author Bernhard Schussek <bschussek@gmail.com>
*/
class InvalidArgumentException extends \InvalidArgumentException implements ExceptionInterface
{
}

View File

@ -0,0 +1,29 @@
<?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\Exception;
/**
* This exception is thrown when the csrf token is invalid.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
* @author Alexander <iam.asm89@gmail.com>
*/
class InvalidCsrfTokenException extends AuthenticationException
{
/**
* {@inheritdoc}
*/
public function getMessageKey()
{
return 'Invalid CSRF token.';
}
}

View File

@ -0,0 +1,34 @@
<?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\Exception;
use Symfony\Component\HttpFoundation\Response;
/**
* A signaling exception that wraps a lazily computed response.
*
* @author Nicolas Grekas <p@tchwork.com>
*/
class LazyResponseException extends \Exception implements ExceptionInterface
{
private $response;
public function __construct(Response $response)
{
$this->response = $response;
}
public function getResponse(): Response
{
return $this->response;
}
}

View File

@ -0,0 +1,29 @@
<?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\Exception;
/**
* LockedException is thrown if the user account is locked.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Alexander <iam.asm89@gmail.com>
*/
class LockedException extends AccountStatusException
{
/**
* {@inheritdoc}
*/
public function getMessageKey()
{
return 'Account is locked.';
}
}

View File

@ -0,0 +1,21 @@
<?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\Exception;
/**
* Base LogicException for the Security component.
*
* @author Iltar van der Berg <kjarli@gmail.com>
*/
class LogicException extends \LogicException implements ExceptionInterface
{
}

View File

@ -0,0 +1,25 @@
<?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\Exception;
/**
* LogoutException is thrown when the account cannot be logged out.
*
* @author Jeremy Mikola <jmikola@gmail.com>
*/
class LogoutException extends RuntimeException
{
public function __construct(string $message = 'Logout Exception', \Throwable $previous = null)
{
parent::__construct($message, 403, $previous);
}
}

View File

@ -0,0 +1,30 @@
<?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\Exception;
/**
* ProviderNotFoundException is thrown when no AuthenticationProviderInterface instance
* supports an authentication Token.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Alexander <iam.asm89@gmail.com>
*/
class ProviderNotFoundException extends AuthenticationException
{
/**
* {@inheritdoc}
*/
public function getMessageKey()
{
return 'No authentication provider found to support the authentication token.';
}
}

View File

@ -0,0 +1,21 @@
<?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\Exception;
/**
* Base RuntimeException for the Security component.
*
* @author Bernhard Schussek <bschussek@gmail.com>
*/
class RuntimeException extends \RuntimeException implements ExceptionInterface
{
}

View File

@ -0,0 +1,35 @@
<?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\Exception;
/**
* This exception is thrown when no session is available.
*
* Possible reasons for this are:
*
* a) The session timed out because the user waited too long.
* b) The user has disabled cookies, and a new session is started on each
* request.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
* @author Alexander <iam.asm89@gmail.com>
*/
class SessionUnavailableException extends AuthenticationException
{
/**
* {@inheritdoc}
*/
public function getMessageKey()
{
return 'No session available, it either timed out or cookies are not enabled.';
}
}

View File

@ -0,0 +1,29 @@
<?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\Exception;
/**
* TokenNotFoundException is thrown if a Token cannot be found.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
* @author Alexander <iam.asm89@gmail.com>
*/
class TokenNotFoundException extends AuthenticationException
{
/**
* {@inheritdoc}
*/
public function getMessageKey()
{
return 'No token could be found.';
}
}

View File

@ -0,0 +1,65 @@
<?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\Exception;
/**
* This exception is thrown if there where too many failed login attempts in
* this session.
*
* @author Wouter de Jong <wouter@wouterj.nl>
*/
class TooManyLoginAttemptsAuthenticationException extends AuthenticationException
{
private $threshold;
public function __construct(int $threshold = null)
{
$this->threshold = $threshold;
}
/**
* {@inheritdoc}
*/
public function getMessageData(): array
{
return [
'%minutes%' => $this->threshold,
'%count%' => (int) $this->threshold,
];
}
/**
* {@inheritdoc}
*/
public function getMessageKey(): string
{
return 'Too many failed login attempts, please try again '.($this->threshold ? 'in %minutes% minute'.($this->threshold > 1 ? 's' : '').'.' : 'later.');
}
/**
* {@inheritdoc}
*/
public function __serialize(): array
{
return [$this->threshold, parent::__serialize()];
}
/**
* {@inheritdoc}
*/
public function __unserialize(array $data): void
{
[$this->threshold, $parentData] = $data;
$parentData = \is_array($parentData) ? $parentData : unserialize($parentData);
parent::__unserialize($parentData);
}
}

View File

@ -0,0 +1,22 @@
<?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\Exception;
/**
* This exception is thrown when an account is reloaded from a provider which
* doesn't support the passed implementation of UserInterface.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
class UnsupportedUserException extends AuthenticationServiceException
{
}

View File

@ -0,0 +1,99 @@
<?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\Exception;
/**
* UserNotFoundException is thrown if a User cannot be found for the given identifier.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Alexander <iam.asm89@gmail.com>
*/
class UserNotFoundException extends AuthenticationException
{
private $identifier;
/**
* {@inheritdoc}
*/
public function getMessageKey()
{
return 'Username could not be found.';
}
/**
* Get the user identifier (e.g. username or email address).
*/
public function getUserIdentifier(): ?string
{
return $this->identifier;
}
/**
* @return string
*
* @deprecated
*/
public function getUsername()
{
trigger_deprecation('symfony/security-core', '5.3', 'Method "%s()" is deprecated, use getUserIdentifier() instead.', __METHOD__);
return $this->identifier;
}
/**
* Set the user identifier (e.g. username or email address).
*/
public function setUserIdentifier(string $identifier): void
{
$this->identifier = $identifier;
}
/**
* @deprecated
*/
public function setUsername(string $username)
{
trigger_deprecation('symfony/security-core', '5.3', 'Method "%s()" is deprecated, use setUserIdentifier() instead.', __METHOD__);
$this->identifier = $username;
}
/**
* {@inheritdoc}
*/
public function getMessageData()
{
return ['{{ username }}' => $this->identifier, '{{ user_identifier }}' => $this->identifier];
}
/**
* {@inheritdoc}
*/
public function __serialize(): array
{
return [$this->identifier, parent::__serialize()];
}
/**
* {@inheritdoc}
*/
public function __unserialize(array $data): void
{
[$this->identifier, $parentData] = $data;
$parentData = \is_array($parentData) ? $parentData : unserialize($parentData);
parent::__unserialize($parentData);
}
}
if (!class_exists(UsernameNotFoundException::class, false)) {
class_alias(UserNotFoundException::class, UsernameNotFoundException::class);
}

Some files were not shown because too many files have changed in this diff Show More