Last active
July 10, 2019 13:56
-
-
Save romaricdrigon/62c58fe85845e592b03c6ab31b82d017 to your computer and use it in GitHub Desktop.
Comment protéger un contrôleur Symfony d'attaques CSRF
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Controller; | |
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; | |
use Symfony\Component\HttpFoundation\Request; | |
use Symfony\Component\Routing\Annotation\Route; | |
use Symfony\Component\Security\Csrf\CsrfToken; | |
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface; | |
class AppController extends AbstractController | |
{ | |
/** | |
* Par choix, on a décidé de ne pas mettre le token en attribut de la route, mais en paramètre GET classique. | |
* @Route("/user/delete/{id}", name="user_delete") | |
* | |
* Note 2: on choisit d'utiliser l'injection de dépendances pour plus découpler notre contrôleur, | |
* mais sinon on pourrait faire $this->get('security.csrf.token_manager') | |
*/ | |
public function deleteAction($id, Request $request, CsrfTokenManagerInterface $csrfTokenManager) | |
{ | |
$token = new CsrfToken('delete', $request->query->get('_csrf_token')); | |
if (!$csrfTokenManager->isTokenValid($token)) { | |
throw $this->createAccessDeniedException('Token CSRF invalide'); | |
} | |
// Code à suivre, on peut supprimer l'utilisateur... | |
// ... | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{# | |
Le nom du token, "delete", doit correspondre au premier argument de CsrfToken | |
et être unique au sein de notre application pour éviter des conflits. | |
#} | |
<a href="{{ path('user_delete', {id: 2, _csrf_token: csrf_token('delete')}) }}">Supprimer</a> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment