Slim3从CSRF中间件中排除路由

Jef*_*eff 2 routing middleware csrf slim-3

我正在建立一个基于slim3框架的网上商店.我需要处理服务器到服务器的POST请求以确认付款是否成功.我将csrf添加到容器中,如下所示:

$container['csrf'] = function($container) {
    return new \Slim\Csrf\Guard;
};
Run Code Online (Sandbox Code Playgroud)

并将其添加到应用程序中,如下所示:

$app->add($container->csrf);
Run Code Online (Sandbox Code Playgroud)

而且效果很好.但是现在我需要能够在某个路径上添加一个例外,这样我才能得到他们发送的帖子请求.到目前为止我找不到合适的解决方案.

有什么建议?

Geo*_*nov 5

如果您需要从中间件中排除一个路由,则有两个选项:

选项1:对您的路线进行分组.

您可以除以下路线之外的所有路线 分组

<?php
$app->group('', function() {

    // All routes declarations....

})->add($container->csrf); // Add middleware to all routes within the group

// Declare your "exceptional" route outside the group
$app->post('my-special-route-that-has-no-csrf-middleware', 'routeProcessor');
Run Code Online (Sandbox Code Playgroud)

选项2:使用您自己的中间件

而不是\Slim\Csrf\Guard直接使用,使用自己的扩展它的中间件.您的中间件将检查路由,如果路由是"特殊"路由,它将跳过.

将此添加到设置中,因为您需要访问中间件中的路由:

$container['settings'] => [
    'determineRouteBeforeAppMiddleware' => true
];
Run Code Online (Sandbox Code Playgroud)

创建扩展orginial的中间件\Slim\Csrf\Guard:

<?php
class MyCsrfMiddleware extends Slim\Csrf\Guard
{
    // This method is processing every request in your application
    public function processRequest($request, $response, $next) {
        // Check if it's your "exceptional" route
        $route = $request->getAttribute('route');
        if ($route == 'my-special-path') {
            // If it is - just pass request-response to the next callable in chain
            return $next($request, $response);
        } else {
            // else apply __invoke method that you've inherited from \Slim\Csrf\Guard
            return $this($request, $response, $next);
        }
    }
}

/////////////

$container['csrf'] = function($container) {
    return new MyCsrfMiddleware; // Now the container returns your middleware under 'csrf' key
};
Run Code Online (Sandbox Code Playgroud)

现在只需将中间件添加到\Slim\App实例:

$app->add('csrf:processRequest');
Run Code Online (Sandbox Code Playgroud)