Skip to content
This repository has been archived by the owner on Nov 17, 2018. It is now read-only.
/ SlimCSRFProtection Public archive

Another CSRF protection middleware for Slim framewok

Notifications You must be signed in to change notification settings

amok/SlimCSRFProtection

Repository files navigation

PREAMBLE

Middleware only for Slim v1 and v2

In times of v1 and v2 there was official middleware

But it didn't really protect your app - algo was wrong

That's why this MW was created

Slim CSRF protection

Simple protection middleware against CSRF attacks for Slim PHP framework.

  • Really protect your app from csr forgery ;)
  • Helpers for forms and jQuery
  • Versions with and without sessions usage

Usage

SlimCSRFProtection

Version with Sessions (must be enabled)

session_start();
$app = new Slim(); // init app
$app->add( new SlimCSRFProtection() );

Also, you can pass custom function as callback:

function show_message() { echo "verification not passed" }

$app->add( new SlimCSRFProtection('show_message') );

SlimCSRFProtectionNoSession

Note, if you use SlimCSRFProtectionNoSession instead of SlimCSRFProtection, you need to pass in constructor as first argument some secret string, which will be used for generating csrf token - it's required. And, optionally, constructor takes function which will be executed if submitted token is not valid.

$app->add( new SlimCSRFProtectionNoSession("It is my secret string!") );

With function:

function show_message() { echo "verification not passed" }

$app->add( new SlimCSRFProtectionNoSession("It is my secret string!", 'show_message') );

Important

SlimCSRFProtectionNoSession generates token, related to your secret string, $_SERVER['REMOTE_ADDR'] and $_SERVER['USER_AGENT'], therefore it is not full protection - users from same subnet takes same token. If it is possible, use SlimCSRFProtection instead of SlimCSRFProtectionNoSession

Usage in View

By default the middleware appends to view three variables:

$csrf_token - random secret token

$csrf_protection_input - <input> for usage in forms (<input type="hidden" value="<?= $csrf_token ?>">)

$csrf_protection_jquery - jquery code, which add 'X_CSRF_TOKEN' header to each jQuery.ajax post request

You can use those in HTML like so

<form action="/login" method="POST">
    <?= $csrf_protection_input ?>
    <input name="login">
    <input name="passwd">
    <input type="submit" value="Submit">
</form>

...
<head>
    <title>Example</title>
    ....
    <?= $csrf_protection_jquery ?>
</head>
...

API

static::create_token() - returns csrf token

$this->is_token_valid($token) - returns true, if token is valid

See also

Slim-Extras: CsrfGuard middleware

About

Another CSRF protection middleware for Slim framewok

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published