首页 文章

从Slim CSRF中间件中排除路由

提问于
浏览
2

我正在开发一个带有Twig前端的基于Slim 3的应用程序,我也在制作REST API .

我已经为整个应用程序实现了slimphp \ Slim-Csrf,但我现在想要从每个“API”路由中排除这个CSRF检查 .

我正在尝试实现这篇文章的"Option 2":Slim3 exclude route from CSRF Middleware

这是代码:

文件App \ Middleware \ CsrfMiddleware.php:

namespace App\Middleware;

class CsrfMiddleware extends \Slim\Csrf\Guard {

    public function processRequest($request, $response, $next) {
        // Check if this route is in the "Whitelist"
        $route = $request->getAttribute('route');

        if ($route->getName() == 'token') {
            var_dump('! problem HERE, this middleware is executed after the CsrfMiddleware !');
            // supposed to SKIP \Slim\Csrf\Guard
            return $next($request, $response);
        } else {
            // supposed to execute \Slim\Csrf\Guard
            return $this($request, $response, $next);
        }
    }
}

文件app \ app.php:

$app = new \Slim\App([
    'settings' => [
        'determineRouteBeforeAppMiddleware' => true
    ]
]);

require('container.php');
require('routes.php');

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

文件app \ container.php:

$container['csrf'] = function ($container) {
    return new App\Middleware\CsrfMiddleware;
};

文件app \ routes.php:

<?php
$app->get('/', \App\PagesControllers\LieuController::class.':home')->setName('home');

$app->post('/api/token', \App\ApiControllers\AuthController::class.'postToken')->setName('token');

当我在http://localhost/slim3/public/api/token上发出POST请求时,我得到了:

CSRF检查失败!字符串(70)"! problem HERE, this middleware is executed after the CsrfMiddleware !"

就像我的CsrfMiddleware在\ Slim \ Csrf \ Guard之后执行一样......

有人有想法吗?

谢谢 .

1 回答

  • 1

    在Slim 3中,中间件是LIFO(后进先出) . 以相反的方向添加中间件:

    之前

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

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

    Noticepublic 目录不应该是网址的一部分

    不正确: http://localhost/slim3/public/api/token

    正确: http://localhost/slim3/api/token

    要跳过中间件中的处理,只需返回$ response对象 .

    // supposed to SKIP \Slim\Csrf\Guard
    return $response;
    

相关问题