2016-02-19 26 views
1

取下中間件特定的路由我加中間件到我的項目在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()); 
}); 

我怎麼能離開例如「/」路線的認證處理的?

謝謝

回答

4

使用路由中間件而不是應用程序中間件。路由中間件將如果路徑當前的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()); 
}); 
}); 
0

呼叫下一個中間件和提前返回如果路線您的白名單相符。例如:

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