Skip to content

Instantly share code, notes, and snippets.

@ftassi
Created December 20, 2019 10:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ftassi/f734fd35f6131b912c41809fe5e295f4 to your computer and use it in GitHub Desktop.
Save ftassi/f734fd35f6131b912c41809fe5e295f4 to your computer and use it in GitHub Desktop.
Protecting your site against CSRF/XSRF attacks
{
"name": "symfony/security-csrf",
"type": "library",
"description": "Symfony Security Component - CSRF Library",
"keywords": [],
"homepage": "https://symfony.com",
"license": "MIT",
"authors": [
{
"name": "Fabien Potencier",
"email": "fabien@symfony.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"require": {
"php": "^7.2.5",
"symfony/security-core": "^4.4|^5.0"
},
"require-dev": {
"symfony/http-foundation": "^4.4|^5.0"
},
"conflict": {
"symfony/http-foundation": "<4.4"
},
"suggest": {
"symfony/http-foundation": "For using the class SessionTokenStorage."
},
"autoload": {
"psr-4": { "Symfony\\Component\\Security\\Csrf\\": "" },
"exclude-from-classmap": [
"/Tests/"
]
},
"minimum-stability": "dev",
"extra": {
"branch-alias": {
"dev-master": "5.0-dev"
}
}
}
<?php
require(__DIR__ . '/vendor/autoload.php');
use Symfony\Component\Security\Csrf\TokenStorage\NativeSessionTokenStorage;
use Symfony\Component\Security\Csrf\CsrfTokenManager;
use Symfony\Component\Security\Csrf\CsrfToken;
use Symfony\Component\Security\Csrf\TokenGenerator\UriSafeTokenGenerator;
session_start();
/**
* @param CsrfTokenManager $tokenManager
*
* @throws Exception
*/
function assertRequestHasValidToken(CsrfTokenManager $tokenManager)
{
if (empty($_POST)) {
return;
}
$receivedToken = new CsrfToken(session_id(), $_POST['__csrf']);
if (!$tokenManager->isTokenValid($receivedToken)) {
throw new \Exception('The token is not valid');
}
}
$tokenGenerator = new UriSafeTokenGenerator();
$tokenStorage = new NativeSessionTokenStorage();
$tokenManager = new CsrfTokenManager($tokenGenerator, $tokenStorage);
$token = $tokenManager->getToken(session_id());
assertRequestHasValidToken($tokenManager);
?>
<h1>Hello, CSRF protected World ;)</h1>
<?php if(!empty($_POST)): ?>
<h2>You have successfully sent some data</h2>
<?php \Symfony\Component\VarDumper\VarDumper::dump($_POST)?>
<?php endif;?>
<form method="post">
<input type="hidden" name="__csrf"
value="<?php echo $token->getValue(); ?>"/>
<input type="text" placeholder="put some data here" name="data">
<input type="submit" value="Send">
</form>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment