flintci / jquery-ujs-bundle
Symfony组件适配器,用于jQuery-ujs和CSRF保护
v0.1.0
2018-02-02 00:41 UTC
Requires
- php: ^7.1
- doctrine/annotations: ^1.6
- symfony/config: ^3.4 || ^4.0
- symfony/dependency-injection: ^3.4 || ^4.0
- symfony/event-dispatcher: ^3.4 || ^4.0
- symfony/http-kernel: ^3.4 || ^4.0
- symfony/security-csrf: ^3.4 || ^4.0
Requires (Dev)
This package is not auto-updated.
Last update: 2024-09-15 04:31:35 UTC
README
Symfony组件适配器,用于jQuery-ujs和CSRF保护。
安装
使用Composer安装组件
composer require flintci/jquery-ujs-bundle
配置
启用组件。如果你使用Symfony Flex,则已自动完成。
// config/bundles.php return [ FlintCI\jQueryUJSBundle\FlintCIjQueryUJSBundle::class => ['all' => true], ];
在
部分添加metas.html.twig
模板文件
{# base.html.twig #} <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> {% include '@FlintCIjQueryUJS/metas.html.twig' %} </head> {# ... #} </html>
最后,使用Yarn或NPM安装jquery-ujs,并包含rails.js文件。
使用Webpack的app.js
文件示例
import 'jquery-ujs';
然后,你就可以开始使用了!
用法
通过编写这个特殊链接开始使用jQuery-ujs:
<a href="{{ path('account_delete') }}" data-method="delete" data-confirm="Are you sure?">
然后在控制器上手动验证CSRF的有效性
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.'); } // ... } }
或直接使用注解
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. } }