Editing
CSRF Validation in AJAX With Symfony
Jump to navigation
Jump to search
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
[[Category:Symfony]] [[Category:PHP]] [[Category:jQuery]] [[Category:JavaScript]] [[Category:Web Development]] == Goal == From a Symfony page, submit POST data including a CSRF token using jQuery, then validate that CSRF token in the controller that handles the request. == Template == `csrf_token()` is a built-in Twig template function with Symfony. Normally it's used with forms. <syntaxhighlight lang="twig"> <div class="hidden" id="csrf-token" data-token="{{ csrf_token('') }}"><!-- --></div> </syntaxhighlight> == JavaScript/jQuery == * Bind an `ajaxSend` handler to the document that will pass along the csrf token in the request headers for every AJAX call. <syntaxhighlight lang="javascript"> $(document).bind('ajaxSend', function(elm, xhr, s){ if (s.type==="POST") { var csrf_token = $(lclSettings.selectors.csrf).data('token'); xhr.setRequestHeader('X-CSRF-Token', csrf_token); } }); </syntaxhighlight> == Symfony controller == Retrieve the CSRF token from the request headers and validate it in the controller.<ref>[http://stackoverflow.com/questions/15044408/how-can-i-check-whether-the-supplied-csrf-token-is-invalid-in-symfony2 How Can I Check Whether The Supplied CSRF Token Is Invalid In Symfony2], Stackoverflow</ref><ref>[http://stackoverflow.com/questions/12054449/symfony-csrf-and-ajax Symfony CSRF and AJAX], Stackoverflow</ref> <syntaxhighlight lang="php"> use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; // ... /** * @Route("/update/completed/{id}", name="_updated_completed") * @ParamConverter("tutorial", class="AppBundle:Tutorial") * @Method("POST") */ public function updateCompletedAction(Request $request, Tutorial $tutorial) { // get the csrf token from the request header $csrf_token = $request->headers->get('x_csrf_token'); // get the object to validate the token $csrf = $this->get('form.csrf_provider'); // validation if ($csrf->isCsrfTokenValid('', $csrf_token)) { // Handle the request and create a json string for the response } else { // Invalid token $response = new Response(json_encode(array( 'error' => 'Invalid request.' ))); } // return JSON response $response->headers->set('Content-Type', 'application/json'); return $response; } </syntaxhighlight> * The `@ParamConverter` annotation causes the id value to automatically be converted into an entity object, but it doesn't have any direct impact on the CSRF logic. * The `@Method` annotation causes only requests using the POST method to be matched. This also doesn't directly impact the CSRF, but it does provide a layer of protection from inspecting the requests. * Get the token string from the headers. * Get a Symfony CSRF provider object to do the validation. * Validate the token and only perform the action if the token is valid. * Returns a JSON string to the script that called this action. == Notes == <references />
Summary:
Please note that all contributions to Littledamien Wiki may be edited, altered, or removed by other contributors. If you do not want your writing to be edited mercilessly, then do not submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource (see
Littledamien Wiki:Copyrights
for details).
Do not submit copyrighted work without permission!
Cancel
Editing help
(opens in new window)
Navigation menu
Personal tools
Not logged in
Talk
Contributions
Create account
Log in
Namespaces
Page
Discussion
English
Views
Read
Edit
View history
More
Search
Navigation
Main page
Recent changes
Random page
Help about MediaWiki
Tools
What links here
Related changes
Special pages
Page information