RememberMeAuthenticationProvider.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Security\Core\Authentication\Provider;
  11. use Symfony\Component\Security\Core\Authentication\Token\RememberMeToken;
  12. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  13. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  14. use Symfony\Component\Security\Core\Exception\BadCredentialsException;
  15. use Symfony\Component\Security\Core\Exception\LogicException;
  16. use Symfony\Component\Security\Core\User\UserCheckerInterface;
  17. use Symfony\Component\Security\Core\User\UserInterface;
  18. class RememberMeAuthenticationProvider implements AuthenticationProviderInterface
  19. {
  20. private $userChecker;
  21. private $secret;
  22. private $providerKey;
  23. /**
  24. * @param string $secret A secret
  25. * @param string $providerKey A provider secret
  26. */
  27. public function __construct(UserCheckerInterface $userChecker, string $secret, string $providerKey)
  28. {
  29. $this->userChecker = $userChecker;
  30. $this->secret = $secret;
  31. $this->providerKey = $providerKey;
  32. }
  33. /**
  34. * {@inheritdoc}
  35. */
  36. public function authenticate(TokenInterface $token)
  37. {
  38. if (!$this->supports($token)) {
  39. throw new AuthenticationException('The token is not supported by this authentication provider.');
  40. }
  41. if ($this->secret !== $token->getSecret()) {
  42. throw new BadCredentialsException('The presented secret does not match.');
  43. }
  44. $user = $token->getUser();
  45. if (!$token->getUser() instanceof UserInterface) {
  46. throw new LogicException(sprintf('Method "%s::getUser()" must return a "%s" instance, "%s" returned.', get_debug_type($token), UserInterface::class, get_debug_type($user)));
  47. }
  48. $this->userChecker->checkPreAuth($user);
  49. $this->userChecker->checkPostAuth($user);
  50. $authenticatedToken = new RememberMeToken($user, $this->providerKey, $this->secret);
  51. $authenticatedToken->setAttributes($token->getAttributes());
  52. return $authenticatedToken;
  53. }
  54. /**
  55. * {@inheritdoc}
  56. */
  57. public function supports(TokenInterface $token)
  58. {
  59. return $token instanceof RememberMeToken && $token->getFirewallName() === $this->providerKey;
  60. }
  61. }