dneustadt / csrf-cookie-bundle

用于 XHR 的 CSRF 保护 Cookie

1.0.7 2023-06-21 11:31 UTC

This package is auto-updated.

Last update: 2024-09-21 13:57:47 UTC


README

Symfony 包为客户端应用程序提供了通过 XHR 请求由 Symfony 提供的端点的跨站请求伪造(CSRF 或 XSRF)保护。

DunglasAngularCsrfBundle 的影响很大,并从中获得灵感。

要求

  • Symfony >= 5.x

工作方式

要在客户端存储 CSRF 令牌,可以通过一个或多个预定义的路由设置包含令牌的 Cookie。该包预先配置,以便现代客户端 HTTP 客户端(如 Axios)将自动捕获此 Cookie。然后在后续请求到 Symfony 后,可以将 CSRF 令牌添加到 HTTP 标头中,以便在服务器端进行验证。再次强调,某些客户端可能已经自动执行此操作,例如 Axios。

安装

使用 Composer 安装此包

composer require dneustadt/csrf-cookie-bundle

通用配置

# config/packages/dneustadt_csrf_cookie.yaml
dneustadt_csrf_cookie:
    # Generally enable/disable the CSRF protection
    enable: true
    # ID used to generate token
    id: csrf
    # Name of the cookie the token is stored in
    name: XSRF-TOKEN
    # Cookie expiration
    expire: 0
    # Cookie path
    path: /
    # Cookie domain
    domain: null
    # Cookie HttpOnly
    httpOnly: true
    # Cookie secure
    secure: false
    # Name of the HTTP header the token is expected to be stored in
    header: X-XSRF-TOKEN
    # Cookie same site policy
    sameSite: lax

路由配置

路由可以设置为提供(创建)令牌、通过(要求)令牌进行安全保护或两者兼具。

由于单个路由或路由集合的默认值用于配置行为,因此可以通过配置文件或注解来实现。

# config/routes.yaml
api_controllers:
    resource: ../src/Controller/Api
    type: annotation
    defaults:
        csrf:
            # bool or array of allowed methods
            create: true
            # bool or array of allowed methods
            require:
                - 'POST'
                - 'PUT'
                - 'PATCH'
                - 'DELETE'
            # array of route names to be excluded from create/require in this collection
            exclude:
                - 'app_api_blog_index'
            # additional condition using ExpressionLanguage syntax
            condition: 'request.isXmlHttpRequest()'

有关条件的更多信息,请参阅 ExpressionLanguage

作为注解

// src/Controller/Api/ExampleController.php
namespace App\Controller\Api;

// ...

class ExampleController extends AbstractController
{
    /**
     * @Route("/api/index", methods={"GET","HEAD"}, defaults={"csrf": {"create": true}})
     */
    public function index()
    {
        // ...
    }
}

Symfony 表单组件

对于配置为通过存储在 HTTP 标头中的令牌进行安全保护的路线,将自动禁用表单的内置 CSRF 保护,前提是令牌可以成功验证。