从 SLIM 中的中间件中删除特定路由


Remove specific routes from middleware in SLIM

>我在项目中添加了中间件

//Initiate a Slim instance
$app = new 'Slim'Slim();
//Add Middleware for authentication
$app->add(new ExampleMiddleware();

但是,我想将一些路由排除在中间件之外。这是我的班级:

class ExampleMiddleware extends Slim'Middleware {
    public function __construct() { 
    //Define the urls that you want to exclude from Authentication
    $this->whiteList =['/'];//This does not work
}

public function call(){
 $res = User::authenticate($token); //Verify user
    if ($res){
        $this->next->call();//Continue to execute the request    
    } else {
        $this->app->response->body(json_encode(['error' => 'denied']));
    }        
}
}
//Sample Route which returns a user from DB using Laravel
$app->get('/', function () use ($app) {
$u = User::find(22078);
$app->response->body($u->toJson());
});

例如,如何将"/"路由排除在身份验证过程之外?

谢谢

使用路由中间件而不是应用程序中间件。仅当路由与当前 HTTP 请求匹配时,才会调用路由中间件,如果您希望中间件仅适用于与身份验证相关的请求,您可以执行以下操作,

$app->get('/authentication_req', function ($req, $res, $args) { echo ' Hello '; })->add(new ExampleMiddleware()); //This will be only applicable for this Route

如果您有许多路由,只需使用组路由并创建一个单独的组,其中包含必须从身份验证中排除的路由,

$app->group('/authentication', function () use ($app) {
 $app->get('/login', function ($request, $response) {
    return $response->getBody()->write(date('Y-m-d H:i:s'));
 });
 $app->get('/logout', function ($request, $response) {
    return $response->getBody()->write(time());
 });
})->add(new ExampleMiddleware()); //should be called like this /authentication/login
//Excluded group
$app->group('/home', function () use ($app) {
 $app->get('/first_page', function ($request, $response) {
    return $response->getBody()->write(date('Y-m-d H:i:s'));
 });
 $app->get('/second_page', function ($request, $response) {
    return $response->getBody()->write(time());
 });
});

调用下一个中间件,如果路由与您的白名单匹配,请提前返回。像这样:

public function call()
{
    /* Check if uri is whitelisted. */
    if ($this->uriInWhitelist()) {
        $this->next->call();
        return;
    }
    /* Authenticate user */
    $result = User::authenticate($token); 
    if ($result) { 
        /* Everything ok, call next middleware. */
        $this->next->call();
    } else { 
        /* Handle error here. */
    }
}

您还可以检查 slim-jwt-auth 的来源以获取实际示例。