PreAuthenticatedAuthenticationProvider.php 2.5 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\PreAuthenticatedToken;
  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\User\UserCheckerInterface;
  16. use Symfony\Component\Security\Core\User\UserProviderInterface;
  17. /**
  18. * Processes a pre-authenticated authentication request.
  19. *
  20. * This authentication provider will not perform any checks on authentication
  21. * requests, as they should already be pre-authenticated. However, the
  22. * UserProviderInterface implementation may still throw a
  23. * UsernameNotFoundException, for example.
  24. *
  25. * @author Fabien Potencier <fabien@symfony.com>
  26. */
  27. class PreAuthenticatedAuthenticationProvider implements AuthenticationProviderInterface
  28. {
  29. private $userProvider;
  30. private $userChecker;
  31. private $providerKey;
  32. public function __construct(UserProviderInterface $userProvider, UserCheckerInterface $userChecker, string $providerKey)
  33. {
  34. $this->userProvider = $userProvider;
  35. $this->userChecker = $userChecker;
  36. $this->providerKey = $providerKey;
  37. }
  38. /**
  39. * {@inheritdoc}
  40. */
  41. public function authenticate(TokenInterface $token)
  42. {
  43. if (!$this->supports($token)) {
  44. throw new AuthenticationException('The token is not supported by this authentication provider.');
  45. }
  46. if (!$user = $token->getUser()) {
  47. throw new BadCredentialsException('No pre-authenticated principal found in request.');
  48. }
  49. $user = $this->userProvider->loadUserByUsername($user);
  50. $this->userChecker->checkPostAuth($user);
  51. $authenticatedToken = new PreAuthenticatedToken($user, $token->getCredentials(), $this->providerKey, $user->getRoles());
  52. $authenticatedToken->setAttributes($token->getAttributes());
  53. return $authenticatedToken;
  54. }
  55. /**
  56. * {@inheritdoc}
  57. */
  58. public function supports(TokenInterface $token)
  59. {
  60. return $token instanceof PreAuthenticatedToken && $this->providerKey === $token->getFirewallName();
  61. }
  62. }