1. Go to this page and download the library: Download solventt/csrf-protection library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
solventt / csrf-protection example snippets
$csrfToken = new MaskedCsrfToken(new SessionTokenStorage(), new SecurityHelper());
$middleware = new CsrfMiddleware($csrfToken, new ResponseFactory());
// then add the middleware to the middlewares stack
// data for a hidden HTML form field
$name = $csrfToken->getName();
$value = $csrfToken->getValue();
$value = $csrfToken->getValue(false);
$value = $csrfToken->getValue(true, 30);
// a default length of the token is 32 chars
$csrfToken->regenerate();
// you can specify a different length
$csrfToken->regenerate(35);
// the DI container definition
// a constructor of the CsrfMiddleware class has 2 mandatory arguments: $token and $responseFactory.
// Thanks to the dependency injection container, the CsrfTokenInterface and ResponseFactoryInterface
// dependencies will be automatically resolved during CsrfMiddleware instantiation
return [
CsrfTokenInterface::class => function (ContainerInterface $c) {
return new MaskedCsrfToken(new SessionTokenStorage(), new SecurityHelper());
},
ResponseFactoryInterface::class => fn () => new ResponseFactory(),
];
/**
* Adding the middleware to the stack
*
* @var Slim\App $app
*/
$app->add(CsrfMiddleware::class);
// the DI container definition
Environment::class => function (ContainerInterface $c) {
...
$csrf = new TwigFunction('csrf', function () use ($c): string {
/** @var MaskedCsrfToken $csrf */
$csrf = $c->get(CsrfTokenInterface::class);
$name = $csrf->getName();
$token = $csrf->getValue();
return sprintf('<input type="hidden" name="%s" value="%s">', $name, $token);
});
$twig->addFunction($csrf);
...
}
...
{{ csrf()|raw }}
...
$csrfToken = new MaskedCsrfToken(
new SessionTokenStorage(),
new SecurityHelper(),
'customTokenName'
);
...
$session = $container->get(SessionInterface::class);
$logger = $container->get(LoggerInterface::class);
$responseFactory = $container->get(ResponseFactoryInterface::class);
$failureHandler = function () use ($session, $logger, $responseFactory): ResponseInterface {
$session->destroy();
$logger->error('CSRF check failed');
$response = $responseFactory->createResponse(403);
$response->getBody()->write('Forbidden');
return $response;
};
$middleware = new CsrfMiddleware(
$csrfToken,
new ResponseFactory(),
$failureHandler
);
interface TokenStorageInterface
{
public function get(string $tokenName): ?string;
public function set(string $tokenName, string $value): void;
public function remove(string $tokenName): void;
}
use Solventt\Csrf\Interfaces\TokenStorageInterface;
use Odan\Session\SessionInterface;
class CsrfSessionTokenStorage implements TokenStorageInterface
{
public function __construct(private SessionInterface $session) {}
public function get(string $tokenName): ?string
{
/** @var mixed|null $value */
$value = $this->session->get($tokenName);
return is_string($value) ? $value : null;
}
public function set(string $tokenName, string $value): void
{
$this->session->set($tokenName, $value);
}
public function remove(string $tokenName): void
{
$this->session->remove($tokenName);
}
interface SecurityInterface
{
/**
* Generates a cryptographically secure value
*/
public function generateToken(int $length): string;
/**
* Applies a random mask to the CSRF token making it unique when its requested
*/
public function addMask(string $token): string;
/**
* Removes the mask from the CSRF token previously masked with the 'addMask' method
*/
public function removeMask(string $token): string;
}
interface CsrfTokenInterface
{
public const DEFAULT_NAME = '_csrf';
public function getName(): string;
public function getValue(): string;
/**
* Compares the token from the request with the token found in a token storage
*/
public function equals(string $requestToken): bool;
}