我正在构建一个基于 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/