Slim-Csrf with Slim 3
In addition to the core Slim framework, we also ship a number of add-ons that are useful for specific types of problems. One of these is Slim-Csrf which provides CSRF protection.
This is middleware that sets a token in the session for every request that you can then set as an hidden input field on a form. When the form is submitted, the middleware checks that the value in the form field matches the value stored in the session. If they match, then the all is okay, but if they don’t then an error is raised.
For the simplest use case, you need start the session and add the middleware:
session_start(); $app->add(new Slim\Csrf\Guard());
Then, from within a given route callable, you can create your form and add two hidden fields: one for the token’s name and one for its value:
$app->get('/', function ($request, $response, $args) { // CSRF token name and value $name = $request->getAttribute('csrf_name'); $value = $request->getAttribute('csrf_value'); // Render a form $html = <<<EOT <!DOCTYPE html> <html> <head><title>CSRF test</title></head> <body> <form method="POST" action="/process"> <input type="hidden" name="csrf_name" value="$name"> <input type="hidden" name="csrf_value" value="$value"> <input type="text" name="name" placeholder="Name"> <input type="submit" value="Go"> </form> </body> </html> EOT; return $response->write($html); });
If you run this in a browser and view the source, you’ll see something like this:
Refresh and you see different values for the csrf_name and csrf_value fields, which means that the user can have multiple tabs open and submit without any issues.
For testing, I created a simple route callable:
$app->post('/process', function ($request, $response, $args) { return $response->write("Passed CSRF check."); });
Pressing form’s submit button will result in the display of “Passed CSRF check.”. If you then refresh and confirm the post, you’ll see “Failed CSRF check!” and the HTTP status code will be 400.
Customising the CSRF failure
It’s likely that you’ll want to customise the CSRF failure display as a plaint text error message isn’t very user friendly! To change this, supply a callable to the Guard class which has the same signature as middleware: `
function($request, $response, $next). The middleware must return a Response.
This allows you to supply a custom error page:
$guard = new Slim\Csrf\Guard(); $guard->setFailureCallable(function ($request, $response, $next) { return $response->write(<<<EOT <!DOCTYPE html> <html> <head><title>CSRF test</title></head> <body> <h1>Error</h1> <p>An error occurred with your form submission. Please start again.</p> </body> </html> EOT); }); $app->add($guard);
As the failure callable has the middleware signature, you can also set a flag into $request and then deal with the CSRF failure later. The failure callable would look something like this:
$guard->setFailureCallable(function ($request, $response, $next) { $request = $request->withAttribute("csrf_result", 'FAILED'); return $next($request, $response); });
Now, your route callable can decide what to do:
$app->post('/process', function ($request, $response, $args) { if (false === $request->getAttribute('csrf_result')) { // Deal with error here and update $response as appropriate } else { // successfully passed CSRF check $response->write("Passed CSRF check."); } return $response; });
This is very powerful and remarkably easy to set up.
Summary
The flexibility of the failure callable allows you to handle a CSRF validation failure in the most appropriate way for your application and is a very powerful feature of this middleware.
As it’s PSR-7 compliant, you can use the middleware independently of Slim with any PSR-7 middleware dispatch system that uses the middleware signature of function($request, $response, $next) where a Response is returned.
In terms of setting a flag, I think your code needs to be updated:
$request = $request->withAttribute("csrf_result", 'FAILED');
to
$request = $request->withAttribute("csrf_result", false);
or checking for 'FAILED' in the route.
if ('FAILED'=== $request->getAttribute('csrf_result')) {