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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With