Slim 4 and slim/csrf

Hi,

How can you register in Slim 4 smlim/csrf. Are there any examples outside of the documentation? How to add csrf to the app/dependencies.php file, because I understand that the csrf configuration should be there?

Thank you for your help.

Yes, the “set” method should not really be used. Instead you may better use the array syntax to add DI container definitions.

Example using the ResponseFactoryInterface DI container definition and nyholm/Psr7:

<?php

use Nyholm\Psr7\Factory\Psr17Factory;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseFactoryInterface;
use Slim\Csrf\Guard;

return [

    Guard::class => function (ContainerInterface $container) {
        $responseFactory = $container->get(ResponseFactoryInterface::class);

        return new Guard($responseFactory);
    },

    ResponseFactoryInterface::class => function (ContainerInterface $container) {
        return $container->get(Psr17Factory::class);
    },
];

Example using the App class within the DI container:

<?php

use Psr\Container\ContainerInterface;
use Slim\App;
use Slim\Csrf\Guard;

return [
   
    App::class => function (ContainerInterface $container) {
        $app = AppFactory::createFromContainer($container);
        // ...

        return $app;
    },

    Guard::class => function (ContainerInterface $container) {
        $responseFactory = $container->get(App::class)->getResponseFactory();

        return new Guard($responseFactory);
    },
];

Register Middleware to be executed on all routes:

$app->add(\Slim\Csrf\Guard::class);
1 Like

This is a great solution. :+1:

Just wondering if there are any ‘more modern’ ways than CSRF?

One I am aware of is SameSite, but there may be others?

Yes, SameSite is a more modern approach.

And should $guard->setFailureHandler still be added… ? I keep getting the message Failed CSRF check!