DigestAuthenticationEntryPoint.php 2.3 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\Http\EntryPoint;
  11. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  12. use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface;
  13. use Symfony\Component\Security\Core\Exception\NonceExpiredException;
  14. use Symfony\Component\HttpFoundation\Response;
  15. use Symfony\Component\HttpFoundation\Request;
  16. use Psr\Log\LoggerInterface;
  17. /**
  18. * DigestAuthenticationEntryPoint starts an HTTP Digest authentication.
  19. *
  20. * @author Fabien Potencier <fabien@symfony.com>
  21. */
  22. class DigestAuthenticationEntryPoint implements AuthenticationEntryPointInterface
  23. {
  24. private $key;
  25. private $realmName;
  26. private $nonceValiditySeconds;
  27. private $logger;
  28. public function __construct($realmName, $key, $nonceValiditySeconds = 300, LoggerInterface $logger = null)
  29. {
  30. $this->realmName = $realmName;
  31. $this->key = $key;
  32. $this->nonceValiditySeconds = $nonceValiditySeconds;
  33. $this->logger = $logger;
  34. }
  35. public function start(Request $request, AuthenticationException $authException = null)
  36. {
  37. $expiryTime = microtime(true) + $this->nonceValiditySeconds * 1000;
  38. $signatureValue = md5($expiryTime.':'.$this->key);
  39. $nonceValue = $expiryTime.':'.$signatureValue;
  40. $nonceValueBase64 = base64_encode($nonceValue);
  41. $authenticateHeader = sprintf('Digest realm="%s", qop="auth", nonce="%s"', $this->realmName, $nonceValueBase64);
  42. if ($authException instanceof NonceExpiredException) {
  43. $authenticateHeader = $authenticateHeader.', stale="true"';
  44. }
  45. if (null !== $this->logger) {
  46. $this->logger->debug(sprintf('WWW-Authenticate header sent to user agent: "%s"', $authenticateHeader));
  47. }
  48. $response = new Response();
  49. $response->headers->set('WWW-Authenticate', $authenticateHeader);
  50. $response->setStatusCode(401);
  51. return $response;
  52. }
  53. public function getKey()
  54. {
  55. return $this->key;
  56. }
  57. public function getRealmName()
  58. {
  59. return $this->realmName;
  60. }
  61. }