schnittstabil/csrf-tokenservice

Stateless CSRF (Cross-Site Request Forgery) token service.

3.1.0 2017-09-05 18:57 UTC

This package is auto-updated.

Last update: 2024-11-26 02:10:32 UTC


README

SensioLabsInsight

Stateless CSRF (Cross-Site Request Forgery) token service 🍖

Install

$ composer require schnittstabil/csrf-tokenservice

Usage

<?php
require __DIR__.'/vendor/autoload.php';

use Schnittstabil\Csrf\TokenService\TokenService;

// Shared secret key used for generating and validating token signatures:
$key = 'This key is not so secret - change it!';

// Time to Live in seconds; default is 1440 seconds === 24 minutes:
$ttl = 1440;

// create the TokenService
$tokenService = new TokenService($key, $ttl);

// generate a URL-safe token, using the name of the authenticated user as nonce:
$token = $tokenService->generate($_SERVER['PHP_AUTH_USER']);

// validate the token - stateless; no session needed
if (!$tokenService->validate($_SERVER['PHP_AUTH_USER'], $token)) {
    http_response_code(403);
    echo '<h2>403 Access Forbidden, bad CSRF token</h2>';
    exit();
}

Related

License

MIT © Michael Mayer