项目作者: julfiker

项目描述 :
A service to handle csrf on POST|PULL\DELETE request for php application
高级语言: PHP
项目地址: git://github.com/julfiker/csrf-php.git
创建时间: 2018-03-22T11:04:31Z
项目社区:https://github.com/julfiker/csrf-php

开源协议:MIT License

下载


csrf-php

Generating csrf token and checking in POST|PULL|DELETE method action. Its independent service for php application. You can integrated it php any kind application.
Scrutinizer Code Quality
Build Status
Code Intelligence Status

Installation

  1. composer require julfiker/csrf-php

Just run composer require command with package name. This assumes you have composer installed and available in your path as composer. Instruction to have composer https://getcomposer.org/doc/00-intro.md.

How to use in plain php application

  1. require_once __DIR__."/vendor/autoload.php";
  2. use Julfiker\Service\CsrfManager as Csrf;
  3. $csrf = new Csrf();
  4. $csrf->setExpiredAt(10); //10 minutes; But default it has 30 minutes
  5. $token = $csrf->getCSRFToken();
  6. $tokenFieldName = $csrf->getTokenFieldName();
  1. <!-- view html template page -->
  2. <form action="post.php" method="post">
  3. <label>Subscribes email</label>
  4. <input type="text" name="email" />
  5. <input type="hidden" value="<?php echo $token?>" name="<?php echo $tokenFieldName?>" />
  6. <button type="submit">Submit</button>
  7. </form>

Checking token in post action

  1. require_once __DIR__."/vendor/autoload.php";
  2. use Julfiker\Service\CsrfManager as Csrf;
  3. $csrf = new Csrf();
  4. if (!$csrf->isValidToken()) { //Is not valid token
  5. echo "Invalid token!";
  6. exit;
  7. }
  8. echo "Token was valid and saving the information";

How to use in zendframework 1.*

In a multiple way you can integrate the csrf token validation for crontroller action

Option 1: You can use customer action helper to check csrf token from controller action specifically
Option 2: Plugin to check csrf on each post action method in general.
Example Action helper

  1. /**
  2. * Action helper checking csrf from action, it can be used in controller action like
  3. *
  4. * $this->_helper->csrf->validateToken()->ifInvalid()->gotoReferer();
  5. * OR
  6. * $this->_helper->csrf->validateToken()->ifInvalid()->gotoUrl('url_str');
  7. * OR
  8. * $csrf = $this->_helper->csrf->validateToken();
  9. * if ($csrf->isInvalidToken())
  10. * $csrf->gotoUrl('url_string');
  11. *
  12. * @author: Julfiker <mail.julfiker@gmail.com>
  13. */
  14. class ProjectNameSpace_Zend_Controller_Action_Helper_Csrf extends Zend_Controller_Action_Helper_Redirector
  15. {
  16. /** @var \Julfiker\Service\CsrfManager */
  17. protected $csrfManager;
  18. /** @var bool */
  19. protected $isValidToken = false;
  20. /** @var \Zend_Controller_Action_Helper_FlashMessenger */
  21. protected $flashMessenger;
  22. public function __construct() {
  23. //Dependency injecting
  24. $this->csrfManager = new \Julfiker\Service\CsrfManager();
  25. $this->flashMessenger = \Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger');
  26. }
  27. /**
  28. * Checking csrf token valid or not
  29. * @return $this
  30. */
  31. public function validateToken() {
  32. $this->isValidToken = $this->getCsrfManager()->isValidToken();
  33. return $this;
  34. }
  35. /**
  36. * @return $this
  37. */
  38. public function ifInvalid() {
  39. return $this;
  40. }
  41. /**
  42. * Redirecting to referer url
  43. */
  44. public function goToReferer() {
  45. if ($this->isInvalidToken()) {
  46. $this->flashMessenger->addMessage(array('error' => "Invalid token!"));
  47. return $this->gotoUrl($_SERVER['HTTP_REFERER']);
  48. }
  49. return $this->isValidToken;
  50. }
  51. /**
  52. * Redirecting to specific url
  53. * @param string $url
  54. * @param array $options
  55. * @return redirect|bool
  56. */
  57. public function gotoUrl($url, array $options = array()) {
  58. if ($this->isInvalidToken()) {
  59. return parent::gotoUrl($url, $options);
  60. }
  61. return $this->isValidToken;
  62. }
  63. /**
  64. * Get Csrf manager instance
  65. */
  66. public function getCsrfManager() {
  67. return $this->csrfManager;
  68. }
  69. /**
  70. * @return bool
  71. */
  72. public function isValidToken() {
  73. return $this->isValidToken;
  74. }
  75. /**
  76. * @return bool
  77. */
  78. public function isInvalidToken() {
  79. return !$this->isValidToken;
  80. }
  81. }

How to use action helper in controller

Controller action example to use action helper

  1. //Checking csrf protection
  2. $this->_helper->csrf->validateToken()
  3. ->ifInvalid()
  4. ->gotoReferer();
  5. //Or
  6. $csrf = $this->_helper->csrf->validateToken();
  7. if ($csrf->isInvalidToken())
  8. $csrf->gotoUrl(‘url_string’);

However, without action helper you can use directly service to check csrf token like following

  1. $csrf = new \Julfiker\Service\CsrfManager();
  2. if (!$csrf->isValidToken()) {
  3. echo "Invalid token!";
  4. exit;
  5. }

Another way to check token in general for all action.
You need to create a controller plugin

Example plugin code*

  1. /**
  2. * Class ProjectNameSpace_Zend_Controller_Plugin_Csrf
  3. */
  4. class ProjectNameSpace_Zend_Controller_Plugin_Csrf extends Zend_Controller_Plugin_Abstract
  5. {
  6. /**
  7. * @param Zend_Controller_Request_Abstract $request
  8. */
  9. public function preDispatch(Zend_Controller_Request_Abstract $request)
  10. {
  11. if ($request->isPost() || $request->isPut() || $request->isDelete()) {
  12. $csrf = new \Julfiker\Service\CsrfManager();
  13. if (!$csrf->isValidToken()) {
  14. //Redirect logic
  15. //Set flash error message here
  16. if ($referer = $request->getHeader('referer')) {
  17. $this->_response->setRedirect($referer);
  18. }
  19. else {
  20. $this->_response->setRedirect("/");
  21. }
  22. }
  23. }
  24. }
  25. }

Note: You have register plugin into application.ini. Or through front controller.

To render html token with hidden input element on each form

I recommend to use view helper to do that.

Example view helper

  1. /**
  2. * Csrf token view helper used to render token
  3. *
  4. * @author: Julfiker <mail.julfiker@gmail.com>
  5. */
  6. class ProjectNameSpace_Zend_View_Helper_CsrfToken extends Zend_View_Helper_Abstract
  7. {
  8. /** @var \Julfiker\Service\CsrfManager */
  9. private $csrfManager;
  10. /**
  11. * View to helper to render csrf token
  12. */
  13. public function csrfToken() {
  14. $this->csrfManager = new \Julfiker\Service\CsrfManager();
  15. //$this->csrfManager->setExpiredAt(30); //Set expired at, Default 30 MINUTES
  16. return $this;
  17. }
  18. /**
  19. * Render token field in html format
  20. * in the template or view page
  21. * @return string as html
  22. */
  23. public function render() {
  24. return "<input type='hidden' name='".$this->getCsrfManager()->getTokenFieldName()."' value='".$this->getCsrfManager()->getCSRFToken()."' />";
  25. }
  26. /**
  27. * @return \managers\CSRFManager
  28. */
  29. public function getCsrfManager() {
  30. return $this->csrfManager;
  31. }
  32. /**
  33. * Get token element for the form object, get specific element object with token value
  34. * @return \Zend_Form_Element_Hidden;
  35. */
  36. public function getElement() {
  37. $token = new Zend_Form_Element_Hidden($this->getCsrfManager()->getTokenFieldName());
  38. $token->setValue($this->csrfManager->getCSRFToken());
  39. return $token;
  40. }
  41. }

How to render token in html view by example view helper code

If you used raw html form, then you can use following code to render token hidden filed

  1. <?php echo $this->csrfToken()->render(); ?>

If you used zend form to render form, then you can use following example code to add token into the form

  1. $csrfToken = $this->getView()->csrfToken()->getElement();
  2. $this->addElement($csrfToken);