programarivm / csrf-shield

This is a simple, framework-agnostic library that protects your PHP web apps from CSRF attacks.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

CSRF Shield

Build Status License: GPL v3

CSRF Shield

This is a simple, framework-agnostic library that helps you protect your PHP web apps from CSRF attacks. CSRF Shield is built on the idea of sending tokens with the POST method only; otherwise the server will respond with a 405 status code (Method Not Allowed).

Remember: It is encouraged not to disclose CSRF tokens in URLs. For further information on disclosing tokens in URLs, please visit OWASP's Cross-Site Request Forgery CSRF Prevention Cheat Sheet.

1. Install

Via composer:

$ composer require programarivm/csrf-shield

2. Instantiation

Make sure that a PHP session is been started already and then use a CsrfShield\Protection object as it is shown below.

To create/store a new CSRF token into the session:

<?php
use CsrfShield\Protection;

session_start();
// ...
(new Protection)->startToken();

To protect a PHP code snippet that responds to a POST request:

<?php
use CsrfShield\Protection;

session_start();
// ...
(new Protection)->validateToken();

3. CsrfShield\Protection Methods

3.1. startToken()

Creates and stores a new CSRF token into the session.

(new Protection)->startToken();

Side Note: The name of the CSRF session variable is _csrf_shield_token by default.

3.2. getToken()

Gets the current CSRF token from the session.

(new Protection)->getToken();

3.3. validateToken()

Validates the incoming CSRF token against the current session's token.

(new Protection)->validateToken();

The token can be read either through $_POST['_csrf_shield_token'], or through $_SERVER['HTTP_X_CSRF_TOKEN'] if an AJAX call is made with an X-CSRF-Token header.

If the token is not valid the server will send a 403 response (Forbidden).

3.4. htmlInput()

HTML input tag with the embedded value of the current CSRF token.

(new Protection)->htmlInput();

Here is an example:

<input type="hidden" name="_csrf_shield_token" id="_csrf_shield_token" value="5b18469018952acd17039f62f310426ceac16d3f" />

4. License

The GNU General Public License.

5. Contributions

Would you help make this library better? Contributions are welcome.

Many thanks.

About

This is a simple, framework-agnostic library that protects your PHP web apps from CSRF attacks.

License:GNU General Public License v3.0


Languages

Language:PHP 100.0%