jQuery UJS bundle
Symfony bundle adapter for jQuery-ujs and CSRF protection., (*1)
, (*2)
, (*3)
, (*4)
Installation
Install the bundle with composer:, (*5)
``` bash
composer require flintci/jquery-ujs-bundle, (*6)
## Configuration
Enable the bundle. It is already done if you use Symfony Flex.
``` php
// config/bundles.php
return [
FlintCI\jQueryUJSBundle\FlintCIjQueryUJSBundle::class => ['all' => true],
];
Add the metas.html.twig
template file on the <head>
part:, (*7)
{# base.html.twig #}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
{% include '@FlintCIjQueryUJS/metas.html.twig' %}
</head>
{# ... #}
</html>
Finally, install jquery-ujs
with Yarn
or NPM
and include the rails.js file., (*8)
Example on a app.js
file using WebPack:, (*9)
import 'jquery-ujs';
Then, you are good to go!, (*10)
Usage
Start using jquery-ujs by writing this special link:, (*11)
<a href="{{ path('account_delete') }}" data-method="delete" data-confirm="Are you sure?">
Then you can manually verify the CSRF validity on the controller:, (*12)
namespace App\Controller;
use FlintCI\jQueryUJSBundle\Security\Csrf\UjsCsrfManager;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
/**
* @Route("/account")
*/
final class AccountController extends Controller
{
/**
* @Route("/")
* @Method("DELETE")
*/
public function deleteAction(UjsCsrfManager $ujsCsrfManager): Response
{
if (!$ujsCsrfManager->isTokenValid()) {
throw new BadRequestHttpException('Invalid token.');
}
// ...
}
}
Or directly with the annotation:, (*13)
namespace App\Controller;
use FlintCI\jQueryUJSBundle\Annotations\UjsCsrf;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
/**
* @Route("/account")
*/
final class AccountController extends Controller
{
/**
* @Route("/")
* @Method("DELETE")
* @UjsCsrf
*/
public function deleteAction(): Response
{
// Nothing to check here. A bad request excpetion will be thrown if the token is invalid.
}
}