Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add CSRF protection to AJAX call on Symfony3?

I'm developing a web where you can 'add friend' another user, like facebook does. For now, I put a link, and when you click on it, an AJAX call is done.

Before persist the new friendship, I check if request is Ajax, but I want to go further and add more security. A page can have more than 10 links (posible requests), so... I don't know if I need only one token, or a token per link.

Another doubt is.... How to generate a token and check if is valid using Symfony? Focused on how generate the token on the initial controller, and then, how to validate on the addFriend controller (that receive the ajax call).

I tried to use this to generate a token:

http://api.symfony.com/3.1/Symfony/Component/Security/Csrf/TokenGenerator/TokenGeneratorInterface.html

And then this to check the token:

https://symfony.com/doc/current/controller/csrf_token_validation.html

But always return that the token is not valid.

like image 237
Isaac Bosca Avatar asked Jul 16 '17 13:07

Isaac Bosca


1 Answers

Finally I find a workaround for my problem.

As @yceruto commented, is possible to generate a csrf token without any form, see this: http://symfony.com/doc/current/reference/twig_reference.html#csrf-token

With this, I can create my links on TWIG on the following way:

<a data-id="{{ user.id }}" class="card-link clickable sendFriendRequest" data-token="{{ csrf_token(user.id) }}">ADD_FRIEND</a>

Then, I do an AJAX call like this:

$('.elementsList').on('click','.sendFriendRequest', function () {

var userId = $(this).data('id');
var token = $(this).data('token');

$.post('/users/sendFriendRequest/'+userId, {token: token}
).done(function (response) {
    //Some code here

}).fail(function (response) {


});

});

Finally, you check if the token is valid on your contoller using the following code:

$token = $request->request->get('token');

$isValidToken = $this->isCsrfTokenValid($townId, $token);

Thanks!

like image 114
Isaac Bosca Avatar answered Oct 23 '22 15:10

Isaac Bosca