Quick Start
Load the plugin by adding the following statement in your project’s :
- public function bootstrap(): void
- {
- parent::bootstrap();
- $this->addPlugin('Authentication');
- }
Add the authentication to the middleware. See the CakePHP documentation on how to usemiddleware if you are not familiar with it.
If one of the configured authenticators was able to validate the credentials,the middleware will add the authentication service to the request object as an.
Next, in your load the Authentication Component:
- // in src/Controller/AppController.php
- public function initialize()
- {
- parent::initialize();
- $this->loadComponent('Authentication.Authentication');
- }
Once you have the middleware applied to your application you’ll need a way forusers to login. A simplistic login action in a would looklike:
- public function login()
- {
- $result = $this->Authentication->getResult();
- // If the user is logged in send them away.
- if ($result->isValid()) {
- $target = $this->Authentication->getLoginRedirect() ?? '/home';
- return $this->redirect($target);
- }
- if ($this->request->is('post') && !$result->isValid()) {
- $this->Flash->error('Invalid username or password');
- }
- }
Then add a simple logout action:
- use Authentication\PasswordHasher\DefaultPasswordHasher;
- class User extends Entity
- {
- // ... other methods
- // Automatically hash passwords when they are changed.
- protected function _setPassword(string $password)
- {
- $hasher = new DefaultPasswordHasher();
- return $hasher->hash($password);
- }
- }