2017 © Pedro Peláez
 

library sd-csrf

image

ob-ivan/sd-csrf

  • Friday, January 12, 2018
  • by ob-ivan
  • Repository
  • 1 Watchers
  • 0 Stars
  • 465 Installations
  • PHP
  • 0 Dependents
  • 0 Suggesters
  • 0 Forks
  • 0 Open issues
  • 4 Versions
  • 58 % Grown

The README.md

A simple unique token utility to prevent cross-site resource forging (CSRF) attacks., (*1)

Installation

composer require ob-ivan/sd-csrf

Usage

The general use case may be outlined as follows: - A controller requests a token, which csrf manager generates and stores in session data under some reconstructable key. - A view prints token value to a hidden input. - User submits a form, which brings token value to form processing controller. - That second controller reconstructs the key and asks manager to verify the token value, and rejects the form if the value differs., (*2)

This reduces chances that the said form would be sent without user's consent., (*3)

Please note that a manager instance may be either provided with dependency injection container, or instantiated at call time as it is currently stateless (which is not guaranteed to hold in future, though)., (*4)

A sample code would be as follows:, (*5)

use SD\Csrf\Manager;

class CommentController {
    public function getFormAction($postId) {
        return $this->render('form.twig', [
            'postId' => $postId,
            'token' => $this->getCsrfManager()->get($this->getTokenKey($postId)),
        ]);
    }

    public function postFormAction($request) {
        $postId = $request->post->get('postId');
        $tokenValue = $request->post->get('token');
        if (!$this->getCsrfManager()->verify($this->getTokenKey($postId), $tokenValue)) {
            return $this->errorResponse('Csrf token verification failed');
        }
        // ...save comment...
    }

    private function getTokenKey($postId) {
        return "post_comment_token_$postId";
    }
}

The corresponding view code:, (*6)

<form action="POST">
    <input type="hidden" name="postId" value="{{ postId }}"/>
    <input type="hidden" name="token" value="{{ token.value }}"/>
    <textarea name="comment"></textarea>
    <button type="submit>Send it already</button>
</form>

The Versions

12/01 2018
18/08 2017

v1.0

1.0.0.0

  Sources   Download

The Requires

 

The Development Requires