PostAuthenticationGuardToken.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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\Guard\Token;
  11. use Symfony\Component\Security\Core\Authentication\Token\AbstractToken;
  12. use Symfony\Component\Security\Core\User\UserInterface;
  13. /**
  14. * Used as an "authenticated" token, though it could be set to not-authenticated later.
  15. *
  16. * If you're using Guard authentication, you *must* use a class that implements
  17. * GuardTokenInterface as your authenticated token (like this class).
  18. *
  19. * @author Ryan Weaver <ryan@knpuniversity.com>
  20. */
  21. class PostAuthenticationGuardToken extends AbstractToken implements GuardTokenInterface
  22. {
  23. private $providerKey;
  24. /**
  25. * @param string $providerKey The provider (firewall) key
  26. * @param string[] $roles An array of roles
  27. *
  28. * @throws \InvalidArgumentException
  29. */
  30. public function __construct(UserInterface $user, string $providerKey, array $roles)
  31. {
  32. parent::__construct($roles);
  33. if (empty($providerKey)) {
  34. throw new \InvalidArgumentException('$providerKey (i.e. firewall key) must not be empty.');
  35. }
  36. $this->setUser($user);
  37. $this->providerKey = $providerKey;
  38. // this token is meant to be used after authentication success, so it is always authenticated
  39. // you could set it as non authenticated later if you need to
  40. $this->setAuthenticated(true);
  41. }
  42. /**
  43. * This is meant to be only an authenticated token, where credentials
  44. * have already been used and are thus cleared.
  45. *
  46. * {@inheritdoc}
  47. */
  48. public function getCredentials()
  49. {
  50. return [];
  51. }
  52. /**
  53. * Returns the provider (firewall) key.
  54. *
  55. * @return string
  56. */
  57. public function getProviderKey()
  58. {
  59. return $this->providerKey;
  60. }
  61. public function getFirewallName(): string
  62. {
  63. return $this->getProviderKey();
  64. }
  65. /**
  66. * {@inheritdoc}
  67. */
  68. public function __serialize(): array
  69. {
  70. return [$this->providerKey, parent::__serialize()];
  71. }
  72. /**
  73. * {@inheritdoc}
  74. */
  75. public function __unserialize(array $data): void
  76. {
  77. [$this->providerKey, $parentData] = $data;
  78. $parentData = \is_array($parentData) ? $parentData : unserialize($parentData);
  79. parent::__unserialize($parentData);
  80. }
  81. }