Codeigniter 4 csrf 过滤器仅用于给定区域中的 post 方法

Codeigniter 4 csrf filter for post methods in given area only

app/Config/Filters.php

您可以为所有 post 方法设置过滤器

public $methods = [
    'post' => ['filter'],
];

或者您可以为给定区域设置过滤器(但所有方法)

public $filters = [
    'filter' => ['before' => ['account/*', 'profiles/*']]
];

如何在给定区域中为 仅 post 方法 设置过滤器?甚至更好除了一个?

我知道个人端点路由是可能的,但我希望找到更多的全球解决方案..

这个怎么样,没有测试,但应该可以。

创建一个从 CSRF 扩展的新过滤器并检查请求方法

namespace App\Filters;

use CodeIgniter\Filters\CSRF;
use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Config\Services;
use Exception;

class CustomCSRF extends CSRF implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        $request = parent::before($request, $arguments);
        try {
            if ($request->getMethod() != "post") {
                throw new Exception("Wrong method");
            }
        } catch (Exception $e) {
            return Services::response()
                ->setJSON([
                    'error' => $e->getMessage()
                ])
                ->setStatusCode(ResponseInterface::HTTP_UNAUTHORIZED);
        }
        return $request;
    }
}

然后将其添加到路由过滤器下

public $aliases = [
    ...
    ...
    'customcsrf' => CustomCSRF::class
];

...
...

public $filters = [
    'customcsrf' => ['before' => ['account/*', 'profiles/*']]
];