定制 yiisoft/csrf 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

yiisoft/csrf

Composer 安装命令:

composer require yiisoft/csrf

包简介

Yii CSRF Protection Library

README 文档

README

Yii

Yii CSRF Protection Library


Latest Stable Version Total Downloads Build status Code coverage Mutation testing badge static analysis type-coverage

The package provides PSR-15 middleware for CSRF protection:

  • It supports two algorithms out of the box:
    • Synchronizer CSRF token with customizable token generation and storage. By default, it uses random data and session.
    • HMAC based token with customizable identity generation. Uses session by default.
  • It has ability to apply masking to CSRF token string to make BREACH attack impossible.
  • It supports CSRF protection by custom header for AJAX/SPA backend API.

Requirements

  • PHP 7.4 - 8.5.

Installation

The package could be installed with Composer:

composer require yiisoft/csrf

General usage

In order to enable CSRF protection you need to add CsrfTokenMiddleware to your main middleware stack. In Yii it is done by configuring MiddlewareDispatcher:

$middlewareDispatcher = $injector->make(MiddlewareDispatcher::class);
$middlewareDispatcher = $middlewareDispatcher->withMiddlewares([
    ErrorCatcher::class,
    SessionMiddleware::class,
    CsrfTokenMiddleware::class, // <-- add this
    Router::class,
]);

or define the MiddlewareDispatcher configuration in the DI container:

// config/web/di/application.php
return [
    MiddlewareDispatcher::class => [
        'withMiddlewares()' => [[
            ErrorCatcher::class,
            SessionMiddleware::class,
            CsrfTokenMiddleware::class, // <-- add this
            Router::class,
        ]]
    ],
];

By default, CSRF token is obtained from _csrf request body parameter or X-CSRF-Token header.

You can access currently valid token as a string using CsrfTokenInterface:

/** @var Yiisoft\Csrf\CsrfTokenInterface $csrfToken */
$csrf = $csrfToken->getValue();

If the token does not pass validation, the response 422 Unprocessable Entity will be returned. You can change this behavior by implementing your own request handler:

use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Yiisoft\Csrf\CsrfTokenMiddleware;

/**
 * @var Psr\Http\Message\ResponseFactoryInterface $responseFactory
 * @var Yiisoft\Csrf\CsrfTokenInterface $csrfToken
 */
 
$failureHandler = new class ($responseFactory) implements RequestHandlerInterface {
    private ResponseFactoryInterface $responseFactory;
    
    public function __construct(ResponseFactoryInterface $responseFactory)
    {
        $this->responseFactory = $responseFactory;
    }

    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        $response = $this->responseFactory->createResponse(400);
        $response
            ->getBody()
            ->write('Bad request.');
        return $response;
    }
};

$middleware = new CsrfTokenMiddleware($responseFactory, $csrfToken, $failureHandler);

By default, CsrfTokenMiddleware considers GET, HEAD, OPTIONS methods as safe operations and doesn't perform CSRF validation. You can change this behavior as follows:

use Yiisoft\Csrf\CsrfTokenMiddleware;
use Yiisoft\Http\Method;

$csrfTokenMiddleware = $container->get(CsrfTokenMiddleware::class);

// Returns a new instance with the specified list of safe methods.
$csrfTokenMiddleware = $csrfTokenMiddleware->withSafeMethods([Method::OPTIONS]);

// Returns a new instance with the specified header name.
$csrfTokenMiddleware = $csrfTokenMiddleware->withHeaderName('X-CSRF-PROTECTION');

or define the CsrfTokenMiddleware configuration in the DI container:

// config/web/di/csrf-token.php
use Yiisoft\Csrf\CsrfTokenMiddleware;
use Yiisoft\Http\Method;

return [
    CsrfTokenMiddleware::class => [
        'withSafeMethods()' => [[Method::OPTIONS]],
        'withHeaderName()' => ['X-CSRF-PROTECTION'],
    ],
];

CSRF Tokens

In case Yii framework is used along with config plugin, the package is configured automatically to use synchronizer token and masked decorator. You can change that depending on your needs.

Use synchronizer token for sensitive anonymous forms; use HMAC token for authenticated-only forms when a submitted token may stay valid for a few minutes.

flowchart TD
    A{Anonymous forms to protect?}
    A -- Yes --> S[Synchronizer]
    A -- No --> B{Old or repeated submits must fail?}
    B -- Yes --> S
    B -- No --> C{Per-environment secret key?}
    C -- No --> S
    C -- Yes --> D{Token replay within lifetime OK?}
    D -- No --> S
    D -- Yes --> H[HMAC]
Loading

Detailed comparison:

Factor Synchronizer HMAC
I/O per request Session read and write No token storage I/O
File based session GC May scan session files Not triggered by CSRF token storage
Token storage growth Depends on session storage Nothing to store
Token revocation Possible by removing stored token Not possible before token expiration
Replay within lifetime Prevented by storage policy Possible until the token expires

To switch token to HMAC:

use Yiisoft\Csrf\CsrfTokenInterface;
use Yiisoft\Csrf\Hmac\HmacCsrfToken;
use Yiisoft\Csrf\MaskedCsrfToken;
use Yiisoft\Definitions\Reference;

return [
    CsrfTokenInterface::class => [
        'class' => MaskedCsrfToken::class,
        '__construct()' => [
            'token' => Reference::to(HmacCsrfToken::class),
        ],
    ],
];

Synchronizer CSRF token

Synchronizer CSRF token is a stateful CSRF token that is a unique random string. It is saved in persistent storage available only to the currently logged-in user. The same token is added to a form. When the form is submitted, token that came from the form is compared against the token stored.

SynchronizerCsrfToken requires implementation of the following interfaces:

  • CsrfTokenGeneratorInterface for generating a new CSRF token;
  • CsrfTokenStorageInterface for persisting a token between requests.

Package provides RandomCsrfTokenGenerator that generates a random token and SessionCsrfTokenStorage that persists a token between requests in a user session.

To learn more about the synchronizer token pattern, check OWASP CSRF cheat sheet.

HMAC based token

HMAC based token is a stateless CSRF token that does not require any storage. The token is a hash from session ID and a timestamp used to prevent replay attacks. The token is added to a form. When the form is submitted, we re-generate the token from the current session ID and a timestamp from the original token. If two hashes match, we check that the timestamp is less than the token lifetime.

HmacCsrfToken requires implementation of CsrfTokenIdentityGeneratorInterface for generating an identity. The package provides SessionCsrfTokenIdentityGenerator that is using session ID thus making the session a token scope.

Parameters set via the HmacCsrfToken constructor are:

  • $secretKey — shared secret key used to generate the hash;
  • $algorithm — hash algorithm for message authentication. sha256, sha384 or sha512 are recommended;
  • $lifetime — number of seconds that the token is valid for.

When using HMAC with the config plugin, configure these constructor arguments through parameters:

return [
    'yiisoft/csrf' => [
        'hmacToken' => [
            'secretKey' => (string) getenv('YII_CSRF_SECRET_KEY'),
            'algorithm' => 'sha256',
            'lifetime' => 300,
        ],
    ],
];

To learn more about HMAC based token pattern check OWASP CSRF cheat sheet.

Stub CSRF token

The StubCsrfToken simply stores and returns a token string. It does not perform any additional validation. This implementation can be useful when mocking CSRF token behavior during unit testing or when providing placeholder functionality in temporary solutions.

Masked CSRF token

MaskedCsrfToken is a decorator for CsrfTokenInterface that applies masking to a token string. It makes BREACH attack impossible, so it is safe to use token in HTML to be later passed to the next request either as a hidden form field or via JavaScript async request.

It is recommended to always use this decorator.

CSRF protection for AJAX/SPA backend API

If you are using a cookie to authenticate your AJAX/SPA, then you do need CSRF protection for the backend API.

Employing custom request header

In this pattern, AJAX/SPA frontend appends a custom header to API requests that require CSRF protection. No token is needed for this approach. This defense relies on the CORS preflight mechanism which sends an OPTIONS request to verify CORS compliance with the destination server. All modern browsers, according to the same-origin policy security model, designate requests with custom headers as "to be preflighted". When the API requires a custom header, you know that the request must have been preflighted if it came from a browser.

The header can be any arbitrary key-value pair, as long as it does not conflict with existing headers. Empty value is also acceptable.

X-CSRF-HEADER=1

When handling the request, the API checks for the existence of this header. If the header does not exist, the backend rejects the request as potential forgery. Employing a custom header allows to reject simple requests that browsers do not designate as "to be preflighted" and permit them to be sent to any origin.

In order to enable CSRF protection you need to add CsrfHeaderMiddleware to the MiddlewareDispatcher configuration:

$middlewareDispatcher = $injector->make(MiddlewareDispatcher::class);
$middlewareDispatcher = $middlewareDispatcher->withMiddlewares([
    ErrorCatcher::class,
    CsrfHeaderMiddleware::class, // <-- add this
    Router::class,
]);

or in the DI container:

// config/web/di/application.php
return [
    MiddlewareDispatcher::class => [
        'withMiddlewares()' => [[
            ErrorCatcher::class,
            CsrfHeaderMiddleware::class, // <-- add this
            Router::class,
        ]]
    ],
];

or add CsrfHeaderMiddleware to the routes that must be protected to the router configuration:

// config/web/di/router.php
return [
    RouteCollectionInterface::class => static function (RouteCollectorInterface $collector) use ($config) {
        $collector
            ->middleware(CsrfHeaderMiddleware::class) // <-- add this
            ->addGroup(Group::create(null)->routes($routes));

        return new RouteCollection($collector);
    },
];

By default, CsrfHeaderMiddleware considers only GET, HEAD, POST methods as unsafe operations. Requests with other HTTP methods trigger CORS preflight and do not require CSRF header validation. You can change this behavior as follows:

use Yiisoft\Csrf\CsrfHeaderMiddleware;
use Yiisoft\Http\Method;

$csrfHeaderMiddleware = $container->get(CsrfHeaderMiddleware::class);

// Returns a new instance with the specified list of unsafe methods.
$csrfHeaderMiddleware = $csrfHeaderMiddleware->withUnsafeMethods([Method::POST]);

// Returns a new instance with the specified header name.
$csrfHeaderMiddleware = $csrfHeaderMiddleware->withHeaderName('X-CSRF-PROTECTION');

or define the CsrfHeaderMiddleware configuration in the DI container:

// config/web/di/csrf-header.php
use Yiisoft\Csrf\CsrfHeaderMiddleware;
use Yiisoft\Http\Method;

return [
    CsrfHeaderMiddleware::class => [
        'withUnsafeMethods()' => [[Method::POST]],
        'withHeaderName()' => ['X-CSRF-PROTECTION'],
    ],
];

The use of a custom request header for CSRF protection is based on the CORS Protocol. Thus, you must configure the CORS module to allow or deny cross-origin access to the backend API.

Warning

CsrfHeaderMiddleware can be used to prevent forgery of same-origin requests and requests from the list of specific origins only.

Protecting same-origin requests

In this scenario:

  • AJAX/SPA frontend and API backend have the same origin.
  • Cross-origin requests to the API server are denied.
  • Simple CORS requests must be restricted.

Configure CORS module

  • Responses to a CORS preflight requests must not contain CORS headers.
  • Responses to an actual requests must not contain CORS headers.

Configure middlewares stack

Add CsrfHeaderMiddleware to the MiddlewareDispatcher configuration:

$middlewareDispatcher = $injector->make(MiddlewareDispatcher::class);
$middlewareDispatcher = $middlewareDispatcher->withMiddlewares([
    ErrorCatcher::class,
    CsrfHeaderMiddleware::class, // <-- add this
    Router::class,
]);

or to the routes that must be protected to the router configuration:

$collector = $container->get(RouteCollectorInterface::class);
$collector->addGroup(
    Group::create('/api')
        ->middleware(CsrfHeaderMiddleware::class) // <-- add this
        ->routes($routes)
);

Configure frontend requests

On the frontend add to the GET, HEAD, POST requests a custom header defined in the CsrfHeaderMiddleware with an empty or random value.

let response = fetch('https://example.com/api/whoami', {
  headers: {
    "X-CSRF-HEADER": crypto.randomUUID()
  }
});

Protecting requests from the list of specific origins

In this scenario:

  • AJAX/SPA frontend and API backend have different origins.
  • Allow cross origin requests to the API server from the list of specific origins only.
  • Simple CORS requests must be restricted.

Configure CORS module

  • A successful responses to a CORS preflight requests must contain appropriate CORS headers.
  • Responses to an actual requests must contain appropriate CORS headers.
  • Value of the CORS header Access-Control-Allow-Origin must contain origin from the predefined list.
// assuming frontend origin is https://example.com and backend origin is https://api.example.com
Access-Control-Allow-Origin: https://example.com

Configure middlewares stack

Add CsrfHeaderMiddleware to the MiddlewareDispatcher configuration:

$middlewareDispatcher = $injector->make(MiddlewareDispatcher::class);
$middlewareDispatcher = $middlewareDispatcher->withMiddlewares([
    ErrorCatcher::class,
    CsrfHeaderMiddleware::class, // <-- add this
    Router::class,
]);

or to the routes that must be protected to the router configuration:

$collector = $container->get(RouteCollectorInterface::class);
$collector->addGroup(
    Group::create('/api')
        ->middleware(CsrfHeaderMiddleware::class) // <-- add this
        ->routes($routes)
);

Configure frontend requests

On the frontend add to the GET, HEAD, POST requests a custom header defined in the CsrfHeaderMiddleware with an empty or random value.

let response = fetch('https://api.example.com/whoami', {
  headers: {
    "X-CSRF-HEADER": crypto.randomUUID()
  }
});

Protecting requests passed from any origin

In this scenario:

  • AJAX/SPA frontend and API backend have different origins.
  • Allow cross origin requests to the API server from any origin.
  • All requests are considered unsafe and must be protected against CSRF with CSRF-token.

Configure CORS module

  • A successful responses to a CORS preflight requests must contain appropriate CORS headers.
  • Responses to an actual requests must contain appropriate CORS headers.
  • The CORS header Access-Control-Allow-Origin has the same value as Origin header in the request.
$frontendOrigin = $request->getOrigin();

Access-Control-Allow-Origin: $frontendOrigin

Configure middlewares stack

By default, CsrfTokenMiddleware considers GET, HEAD, OPTIONS methods as safe operations and doesn't perform CSRF validation. In JavaScript-based apps, requests are made programmatically; therefore, to increase application protection, the only OPTIONS method can be considered safe and need not be appended with a CSRF token header.

Configure CsrfTokenMiddleware safe methods:

use Yiisoft\Csrf\CsrfTokenMiddleware;
use Yiisoft\Http\Method;

$csrfTokenMiddleware = $container->get(CsrfTokenMiddleware::class);
$csrfTokenMiddleware = $csrfTokenMiddleware->withSafeMethods([Method::OPTIONS]);

or in the DI container:

// config/web/di/csrf-token.php
use Yiisoft\Csrf\CsrfTokenMiddleware;
use Yiisoft\Http\Method;

return [
    CsrfTokenMiddleware::class => [
        'withSafeMethods()' => [[Method::OPTIONS]],
    ],
];

Add CsrfTokenMiddleware to the MiddlewareDispatcher configuration:

$middlewareDispatcher = $injector->make(MiddlewareDispatcher::class);
$middlewareDispatcher = $middlewareDispatcher->withMiddlewares([
    ErrorCatcher::class,
    SessionMiddleware::class,
    CsrfTokenMiddleware::class, // <-- add this
    Router::class,
]);

or to the routes that must be protected to the router configuration:

$collector = $container->get(RouteCollectorInterface::class);
$collector->addGroup(
    Group::create('/api')
        ->middleware(CsrfTokenMiddleware::class) // <-- add this
        ->routes($routes)
);

Configure routes

Create a route for acquiring CSRF-tokens from the frontend application to the router configuration.

use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Yiisoft\Http\Header;
use Yiisoft\Http\Method;
use Yiisoft\Router\Route;

Route::options('/csrf-token')
    ->action(static function (
        ResponseFactoryInterface $responseFactory,
        CsrfTokenInterface $token
    ): ResponseInterface {
        $tokenValue = $token->getValue();

        $response = $responseFactory->createResponse()
            ->withHeader(Header::ALLOW, Method::OPTIONS)
            ->withHeader('X-CSRF-TOKEN', $tokenValue);

        $response->getBody()->write($tokenValue);

        return $response;
    }),

Configure frontend requests

On the frontend first make a request to the configured endpoint and acquire a CSRF-token to use it in the subsequent requests.

let response = await fetch('https://api.example.com/csrf-token');

let csrfToken = await response.text();
// OR
let csrfToken = response.headers.get('X-CSRF-TOKEN');

Add to all requests a custom header defined in the CsrfTokenMiddleware with acquired CSRF-token value.

let response = fetch('https://api.example.com/whoami', {
  headers: {
    "X-CSRF-TOKEN": csrfToken
  }
});

Documentation

If you need help or have a question, the Yii Forum is a good place for that. You may also check out other Yii Community Resources.

License

The Yii CSRF Protection Library is free software. It is released under the terms of the BSD License. Please see LICENSE for more information.

Maintained by Yii Software.

Support the project

Open Collective

Follow updates

Official website Twitter Telegram Facebook Slack

yiisoft/csrf 适用场景与选型建议

yiisoft/csrf 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 274.54k 次下载、GitHub Stars 达 27, 最近一次更新时间为 2020 年 09 月 09 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「middleware」 「csrf」 「hmac」 「stateless」 「synchronizer」 「psr-15」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 yiisoft/csrf 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 yiisoft/csrf 我们能提供哪些服务?
定制开发 / 二次开发

基于 yiisoft/csrf 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 274.54k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 27
  • 点击次数: 38
  • 依赖项目数: 27
  • 推荐数: 0

GitHub 信息

  • Stars: 27
  • Watchers: 13
  • Forks: 9
  • 开发语言: PHP

其他信息

  • 授权协议: BSD-3-Clause
  • 更新时间: 2020-09-09