DefaultCsrfProvider.php 1.7 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\Form\Extension\Csrf\CsrfProvider;
  11. /**
  12. * Default implementation of CsrfProviderInterface
  13. *
  14. * This provider uses the session ID returned by session_id() as well as a
  15. * user-defined secret value to secure the CSRF token.
  16. *
  17. * @author Bernhard Schussek <bernhard.schussek@symfony.com>
  18. */
  19. class DefaultCsrfProvider implements CsrfProviderInterface
  20. {
  21. /**
  22. * A secret value used for generating the CSRF token
  23. * @var string
  24. */
  25. protected $secret;
  26. /**
  27. * Initializes the provider with a secret value
  28. *
  29. * A recommended value for the secret is a generated value with at least
  30. * 32 characters and mixed letters, digits and special characters.
  31. *
  32. * @param string $secret A secret value included in the CSRF token
  33. */
  34. public function __construct($secret)
  35. {
  36. $this->secret = $secret;
  37. }
  38. /**
  39. * {@inheritDoc}
  40. */
  41. public function generateCsrfToken($pageId)
  42. {
  43. return sha1($this->secret.$pageId.$this->getSessionId());
  44. }
  45. /**
  46. * {@inheritDoc}
  47. */
  48. public function isCsrfTokenValid($pageId, $token)
  49. {
  50. return $token === $this->generateCsrfToken($pageId);
  51. }
  52. /**
  53. * Returns the ID of the user session
  54. *
  55. * Automatically starts the session if necessary.
  56. *
  57. * @return string The session ID
  58. */
  59. protected function getSessionId()
  60. {
  61. if (!session_id()) {
  62. session_start();
  63. }
  64. return session_id();
  65. }
  66. }