X509Authenticator.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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\Http\Authenticator;
  11. use Psr\Log\LoggerInterface;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  14. use Symfony\Component\Security\Core\Exception\BadCredentialsException;
  15. use Symfony\Component\Security\Core\User\UserProviderInterface;
  16. /**
  17. * This authenticator authenticates pre-authenticated (by the
  18. * webserver) X.509 certificates.
  19. *
  20. * @author Wouter de Jong <wouter@wouterj.nl>
  21. * @author Fabien Potencier <fabien@symfony.com>
  22. *
  23. * @final
  24. * @experimental in 5.2
  25. */
  26. class X509Authenticator extends AbstractPreAuthenticatedAuthenticator
  27. {
  28. private $userKey;
  29. private $credentialsKey;
  30. public function __construct(UserProviderInterface $userProvider, TokenStorageInterface $tokenStorage, string $firewallName, string $userKey = 'SSL_CLIENT_S_DN_Email', string $credentialsKey = 'SSL_CLIENT_S_DN', ?LoggerInterface $logger = null)
  31. {
  32. parent::__construct($userProvider, $tokenStorage, $firewallName, $logger);
  33. $this->userKey = $userKey;
  34. $this->credentialsKey = $credentialsKey;
  35. }
  36. protected function extractUsername(Request $request): string
  37. {
  38. $username = null;
  39. if ($request->server->has($this->userKey)) {
  40. $username = $request->server->get($this->userKey);
  41. } elseif (
  42. $request->server->has($this->credentialsKey)
  43. && preg_match('#emailAddress=([^,/@]++@[^,/]++)#', $request->server->get($this->credentialsKey), $matches)
  44. ) {
  45. $username = $matches[1];
  46. }
  47. if (null === $username) {
  48. throw new BadCredentialsException(sprintf('SSL credentials not found: %s, %s', $this->userKey, $this->credentialsKey));
  49. }
  50. return $username;
  51. }
  52. }