我在项目中添加了中间件
//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());
});
如何将“/”路由退出身份验证过程?
由于
答案 0 :(得分:5)
使用Route中间件而不是Application中间件。仅当路由与当前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());
});
});
答案 1 :(得分: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的来源以获取实际示例。