Developing software in the Real World

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:

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:

If you run this in a browser and view the source, you’ll see something like this:

Slim csrf view source

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:

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:

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:

Now, your route callable can decide what to do:

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.

One thought on “Slim-Csrf with Slim 3

  1. 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')) {

Thoughts? Leave a reply

Your email address will not be published. Required fields are marked *