PHP code example of rafalmasiarek / csrf-token

1. Go to this page and download the library: Download rafalmasiarek/csrf-token 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/ */

    

rafalmasiarek / csrf-token example snippets


use rafalmasiarek\Csrf\Csrf;

session_start();

$csrf = new Csrf($masterKey32Bytes, 900); // TTL=900s
$token = $csrf->generate();               // default container
// <input type="hidden" name="_csrf" value="$token">

if (!$csrf->validate($_POST['_csrf'] ?? null)) {
    http_response_code(419);
    exit('CSRF verification failed');
}

use rafalmasiarek\Csrf\{Csrf, CsrfCacheWrapper, FileStorage};

$csrf = (new Csrf($masterKey32Bytes, 900))
    ->withContainer('signup', ['prefix' => 'auth_', 'bind_ip' => true,  'bind_ua' => true])
    ->withContainer('profile', ['prefix' => 'user_', 'bind_ip' => false, 'bind_ua' => true]);

$cache = new FileStorage(__DIR__ . '/var/csrf-cache'); // or MysqlStorage / RedisStorage
$csrfCached = new CsrfCacheWrapper($csrf, $cache);

// View:
$tokenSignup = $csrfCached->generateFor('signup');
$tokenProfile = $csrfCached->generateFor('profile');

// POST handler:
$ok = $csrfCached->validateFor('signup', $_POST['_csrf'] ?? '');

$token = $csrf->generate($realIp, $realUa);
$isValid = $csrf->validate($submittedToken, $realIp, $realUa);

$token = $csrf->generateFor('signup', $realIp, $realUa);
$ok = $csrf->validateFor('signup', $submittedToken, $realIp, $realUa);

use rafalmasiarek\Csrf\ClientContextProviderInterface;

class SlimRequestProvider implements ClientContextProviderInterface {
    public function __construct(private \Psr\Http\Message\ServerRequestInterface $request) {}

    public function getIp(): string {
        return $this->request->getAttribute('client_ip') ?? '';
    }

    public function getUserAgent(): string {
        return $this->request->getHeaderLine('User-Agent');
    }
}

$csrf = new Csrf($key, 900, new SlimRequestProvider($request));

$csrf = (new Csrf($masterKey32Bytes, 900))
    ->withContainer('transfer-funds', [
        'bind_ip' => false,
        'bind_ua' => true,
        'origin'  => 'https://app.example.com', // trusted, static — never from a request header
    ]);

$token = $csrf->generateFor('transfer-funds');
// throws \RuntimeException at generation time if 'origin' is set but does not
// normalize to a valid http(s) origin (fail loud on misconfiguration)

$ok = $csrf->validateFor(
    'transfer-funds',
    $_POST['_csrf'] ?? null,
    null,
    null,
    $_SERVER['HTTP_ORIGIN'] ?? null // or omit — resolved automatically via OriginProviderInterface
);

$csrf = (new Csrf($masterKey32Bytes, 900))
    ->withContainer('checkout', [
        'allowed_origins' => ['https://app.example.com', '*.example.com'],
        'origin_mode'     => 'strict', // 'strict': missing origin = reject; 'lenient' (default): missing origin = accept
    ]);

// The app issuing tokens — still has its own master key for every other container.
$csrf = (new Csrf($masterKey32Bytes, 900))
    ->withContainer('side-app', ['private_key' => $sideAppKey32Bytes]);

// A separately deployed consumer — only ever holds $sideAppKey32Bytes, never $masterKey32Bytes.
$sideCsrf = (new Csrf($anyUnrelated32ByteKey, 900))
    ->withContainer('side-app', ['private_key' => $sideAppKey32Bytes]);

$token = $csrf->generateFor('side-app');
$sideCsrf->validateFor('side-app', $token); // true — the two instances share only this one key

$csrf = (new Csrf($masterKey32Bytes, 900))
    ->withContainer('transfer-funds', ['f from another:
$pair = $csrf->issueFor('transfer-funds');
// <input type="hidden" name="_csrf" value="<?= $pair->token 

use rafalmasiarek\Csrf\SessionBindingProviderInterface;

final class JwtSessionBindingProvider implements SessionBindingProviderInterface
{
    public function __construct(private string $jwtSessionClaim) {}

    public function getSessionBinding(): string
    {
        return $this->jwtSessionClaim; // must change on login/logout/privilege elevation
    }
}

$csrf = new Csrf($masterKey32Bytes, 900, null, new JwtSessionBindingProvider($claim));

// GET /csrf/refresh?container=checkout
$pair = $csrf->issueFor($_GET['container'] ?? 'default');

header('Content-Type: application/json');
header('Cache-Control: no-store, private');
echo json_encode(['csrf' => $pair->token, 'csrf_proof' => $pair->proof]);

$secondsLeft = $csrf->getExpiresInFor('checkout'); // null = no token yet, 0 = expired, PHP_INT_MAX = TTL disabled

use League\Plates\Engine;
use rafalmasiarek\Csrf\Csrf;
use rafalmasiarek\Csrf\Helpers\Plates\CsrfExtension;

$view = new Engine(__DIR__.'/views');
$csrf = new Csrf($masterKey, 900);
CsrfExtension::register($view, $csrf);

// In template: <?= csrf_field('signup') 

use Twig\Environment;
use Twig\Loader\FilesystemLoader;
use rafalmasiarek\Csrf\Csrf;
use rafalmasiarek\Csrf\Helpers\Twig\CsrfExtension;

$twig = new Environment(new FilesystemLoader(__DIR__.'/views'));
$csrf = new Csrf($masterKey, 900);
$twig->addExtension(new CsrfExtension($csrf));

// In template: {{ csrf_field('signup')|raw }}

use Illuminate\View\Compilers\BladeCompiler;
use rafalmasiarek\Csrf\Csrf;
use rafalmasiarek\Csrf\Helpers\Blade\CsrfBlade;

// In a service provider boot():
CsrfBlade::register($this->app->make(BladeCompiler::class), app(Csrf::class));

// In Blade: @csrfField('signup')
bash
composer