Reputation: 33
Hy guys!
I haven’t been using Cake from gen 2 so i am a bit stuck with all the new stuff. I added the Authentication Component to my project and it works fine (login/out/pass hash etc) but i can’t seem to find how to make only the “Admin” prefix to require Authentication.
In the old times was something “simple” like:
if($this->params[‘prefix’] == ‘admin’){
$this->Auth->deny(’*’);
}
Upvotes: 3
Views: 2330
Reputation: 1
I don't know if this is a conventional method, but it works.
In the callback method beforeFilter
, in my global Appcontroller.php
, I had this code:
public function beforeFilter(\Cake\Event\EventInterface $event)
{
if($this->request->getParam('prefix') == 'Api') {
$this->Authentication->allowUnauthenticated([$this->request->getParam('action')]);
}
}
}
It allows access to all methods of my prefix
API.
Upvotes: 0
Reputation: 60453
While you could do something similar with the authentication plugin's authentication component, authentication is now performed at middleware level, that is before a controller is being invoked, hence it is probably best to avoid trying to authenticate a user in the first place when it's not actually needed.
With the authentication plugin there's a few way to handle this, the easiest way would probably be to apply the authentication middleware on routing level, so that it is scoped to your prefixed routes.
You'd just remove adding the middleware in your Application::middleware()
method (src/Application.php
), and instead add it in either your config/routes.php
file, or your Application::routes()
method, depending on where you're connecting your prefix route:
$routes->prefix('Admin', function (RouteBuilder $routes) {
$routes->registerMiddleware(
'auth',
new \Authentication\Middleware\AuthenticationMiddleware($this)
);
$routes->applyMiddleware('auth');
// ...
});
This way only the routes connected in that prefix are going have authentication applied.
As a second step you'd still need to handle checking for the possibly authenticated user, so that your endpoints are actually protected. By default the authentication component will do automatically, so one way would be to load the authentication component only for the Admin
prefix, for example in your AppController::initialize()
method:
if ($this->request->getParam('prefix') === 'Admin') {
$this->loadComponent('Authentication.Authentication');
}
Note the capital A
in Admin
! In CakePHP 4.x prefixes on are now camel cased, while the generated URLs are lower cased and dash separated!
Upvotes: 5