smilly92
smilly92

Reputation: 2443

HttpBasicAuth inside of a Slim route

I'm trying the authenticate a specific Slim route using the BasicHttpAuth middleware in Slim Extras

This works, however it requires all routes to authenticate:

$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();

So how can you authenticate a single route using HttpBasicAuth?

Upvotes: 3

Views: 3638

Answers (1)

Tobias Snoad
Tobias Snoad

Reputation: 330

You can do it by creating a custom middleware based on HttpBasicAuth, that only runs for a specific route:

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');

Thanks to http://help.slimframework.com/discussions/questions/296-middleware-usage-only-on-specific-routes

Upvotes: 4

Related Questions