Php HttpBasicAuth位于细长路线内

Php HttpBasicAuth位于细长路线内,php,slim,basic-authentication,Php,Slim,Basic Authentication,我正在尝试使用中的中间件对特定的Slim路由进行身份验证 这是可行的,但需要所有路由进行身份验证: $app = new Slim(); $app->add(new HttpBasicAuth('username', 'password')); $app->get('/', function() use ($app) { $app->render('index.php'); }); $app->get('/admin', function() use ($app)

我正在尝试使用中的中间件对特定的Slim路由进行身份验证

这是可行的,但需要所有路由进行身份验证:

$app = new Slim();
$app->add(new HttpBasicAuth('username', 'password'));

$app->get('/', function() use ($app) {
  $app->render('index.php');
});

$app->get('/admin', function() use ($app) {
  $app->render('admin.php');
});

$app->run();

那么,如何使用HttpBasicAuth对单个路由进行身份验证呢?

您可以通过创建基于HttpBasicAuth的自定义中间件来实现身份验证,该中间件只针对特定路由运行:

class HttpBasicAuthCustom extends \Slim\Extras\Middleware\HttpBasicAuth {
    protected $route;

    public function __construct($username, $password, $realm = 'Protected Area', $route = '') {
        $this->route = $route;
        parent::__construct($username, $password, $realm);        
    }

    public function call() {
        if(strpos($this->app->request()->getPathInfo(), $this->route) !== false) {
            parent::call();
            return;
        }
        $this->next->call();
    }
}

$app->add(new HttpBasicAuthCustom('username', 'password', 'Some Realm Name', 'someroute'));

$app->get('/someroute', function () use ($app) {
    echo "Welcome!";
})->name('someroute');
多亏了