DefaultCsrfProvider.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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\Form\Extension\Csrf\CsrfProvider;
  11. @trigger_error('The '.__NAMESPACE__.'\DefaultCsrfProvider is deprecated since Symfony 2.4 and will be removed in version 3.0. Use the \Symfony\Component\Security\Csrf\TokenStorage\NativeSessionTokenStorage class instead.', E_USER_DEPRECATED);
  12. /**
  13. * Default implementation of CsrfProviderInterface.
  14. *
  15. * This provider uses the session ID returned by session_id() as well as a
  16. * user-defined secret value to secure the CSRF token.
  17. *
  18. * @author Bernhard Schussek <bschussek@gmail.com>
  19. *
  20. * @deprecated since version 2.4, to be removed in 3.0.
  21. * Use {@link \Symfony\Component\Security\Csrf\CsrfTokenManager} in
  22. * combination with {@link \Symfony\Component\Security\Csrf\TokenStorage\NativeSessionTokenStorage}
  23. * instead.
  24. */
  25. class DefaultCsrfProvider implements CsrfProviderInterface
  26. {
  27. protected $secret;
  28. /**
  29. * Initializes the provider with a secret value.
  30. *
  31. * A recommended value for the secret is a generated value with at least
  32. * 32 characters and mixed letters, digits and special characters.
  33. *
  34. * @param string $secret A secret value included in the CSRF token
  35. */
  36. public function __construct($secret)
  37. {
  38. $this->secret = $secret;
  39. }
  40. /**
  41. * {@inheritdoc}
  42. */
  43. public function generateCsrfToken($intention)
  44. {
  45. return sha1($this->secret.$intention.$this->getSessionId());
  46. }
  47. /**
  48. * {@inheritdoc}
  49. */
  50. public function isCsrfTokenValid($intention, $token)
  51. {
  52. $expectedToken = $this->generateCsrfToken($intention);
  53. return hash_equals($expectedToken, $token);
  54. }
  55. /**
  56. * Returns the ID of the user session.
  57. *
  58. * Automatically starts the session if necessary.
  59. *
  60. * @return string The session ID
  61. */
  62. protected function getSessionId()
  63. {
  64. if (\PHP_VERSION_ID >= 50400) {
  65. if (PHP_SESSION_NONE === session_status()) {
  66. session_start();
  67. }
  68. } elseif (!session_id()) {
  69. session_start();
  70. }
  71. return session_id();
  72. }
  73. }