routes - Slim3 从 CSRF 中间件中排除路由

标签 routes csrf middleware slim-3

我正在构建一个基于 slim3 框架的网上商店。我需要处理服务器到服务器的 POST 请求以确认付款是否成功。我像这样将 csrf 添加到容器中:

$container['csrf'] = function($container) {
    return new \Slim\Csrf\Guard;
};

并像这样将其添加到应用中:

$app->add($container->csrf);

而且效果很好。但现在我需要能够向特定路线添加异常(exception),以便我收到他们发送的帖子请求。 到目前为止,我找不到可行的解决方案。

有什么建议吗?

最佳答案

如果您需要从中间件中排除一条路由,有两种选择:

选项 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');

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

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

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

$container['settings'] => [
    'determineRouteBeforeAppMiddleware' => true
];

创建扩展原始 \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
};

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

$app->add('csrf:processRequest');

关于routes - Slim3 从 CSRF 中间件中排除路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40203011/

相关文章:

php - laravel undefined variable 保护

node.js - 处理快速中间件模块中的错误

javascript - Express:为 app.use 抽象出中间件

ruby-on-rails - 如何使资源重定向到rails中的另一个 Controller

javascript - 范围错误: Maximum call stack size exceeded (Angular)

ruby-on-rails - 使用 Ruby on Rails 缓存登录表单

javascript - 第二次 ajax 发布时 Laravel csrf token 不匹配

javascript - 为 Angular 2 中的路由通用组件提供异步依赖关系。路由的解析等效项

java - 如何将动态网站(java,spring)作为另一个网站(java)中的网页加载

node.js - 注销并获取 new/csrfToken 后 SailsJS CSRF 不匹配