Quick Start

Install the plugin with composer from your CakePHPProject’s ROOT directory (where the composer.json file is located)

  1. php composer.phar require cakephp/authentication:^2.0

Load the plugin by adding the following statement in your project’s src/Application.php:

  1. public function bootstrap(): void
  2. {
  3. parent::bootstrap();
  4.  
  5. $this->addPlugin('Authentication');
  6. }

Getting Started

Add the authentication to the middleware. See the CakePHP documentation on how to usemiddleware if you are not familiar with it.

Example of configuring the authentication middleware using authentication application hook:

  1. use Authentication\AuthenticationService;
  2. use Authentication\AuthenticationServiceInterface;
  3. use Authentication\AuthenticationServiceProviderInterface;
  4. use Authentication\Middleware\AuthenticationMiddleware;
  5. use Cake\Http\MiddlewareQueue;
  6. use Psr\Http\Message\ServerRequestInterface;
  7.  
  8. class Application extends BaseApplication implements AuthenticationServiceProviderInterface
  9. {
  10. /**
  11. * Returns a service provider instance.
  12. *
  13. * @param \Psr\Http\Message\ServerRequestInterface $request Request
  14. * @return \Authentication\AuthenticationServiceInterface
  15. */
  16. public function getAuthenticationService(ServerRequestInterface $request): AuthenticationServiceInterface
  17. {
  18. $service = new AuthenticationService();
  19.  
  20. $fields = [
  21. 'username' => 'email',
  22. 'password' => 'password'
  23. ];
  24.  
  25. // Load identifiers
  26. $service->loadIdentifier('Authentication.Password', compact('fields'));
  27.  
  28. // Load the authenticators, you want session first
  29. $service->loadAuthenticator('Authentication.Session');
  30. $service->loadAuthenticator('Authentication.Form', [
  31. 'fields' => $fields,
  32. 'loginUrl' => '/users/login'
  33. ]);
  34.  
  35. return $service;
  36. }
  37.  
  38. /**
  39. * Setup the middleware queue your application will use.
  40. *
  41. * @param \Cake\Http\MiddlewareQueue $middlewareQueue The middleware queue.
  42. * @return \Cake\Http\MiddlewareQueue The updated middleware queue.
  43. */
  44. public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue
  45. {
  46. // Various other middlewares for error handling, routing etc. added here.
  47.  
  48. // Create an authentication middleware object
  49. $authentication = new AuthenticationMiddleware($this);
  50.  
  51. // Add the middleware to the middleware queue.
  52. // Authentication should be added *after* RoutingMiddleware.
  53. // So that subdirectory information and routes are loaded.
  54. $middlewareQueue->add($authentication);
  55.  
  56. return $middlewareQueue;
  57. }
  58. }

If one of the configured authenticators was able to validate the credentials,the middleware will add the authentication service to the request object as anattribute.

Next, in your AppController load the Authentication Component:

  1. // in src/Controller/AppController.php
  2. public function initialize()
  3. {
  4. parent::initialize();
  5.  
  6. $this->loadComponent('Authentication.Authentication');
  7. }

By default the component will require an authenticated user for all actions.You can disable this behavior in specific controllers usingallowUnauthenticated():

  1. // in a controller beforeFilter or initialize
  2. // Make view and index not require a logged in user.
  3. $this->Authentication->allowUnauthenticated(['view', 'index']);

Building a Login Action

Once you have the middleware applied to your application you’ll need a way forusers to login. A simplistic login action in a UsersController would looklike:

  1. public function login()
  2. {
  3. $result = $this->Authentication->getResult();
  4. // If the user is logged in send them away.
  5. if ($result->isValid()) {
  6. $target = $this->Authentication->getLoginRedirect() ?? '/home';
  7. return $this->redirect($target);
  8. }
  9. if ($this->request->is('post') && !$result->isValid()) {
  10. $this->Flash->error('Invalid username or password');
  11. }
  12. }

Then add a simple logout action:

  1. public function logout()
  2. {
  3. $this->Authentication->logout();
  4. return $this->redirect(['controller' => 'Users', 'action' => 'login']);
  5. }

In order to login your users will need to have hashed passwords. You canautomatically hash passwords when users update their password using an entitysetter method:

  1. // in src/Model/Entity/User.php
  2. use Authentication\PasswordHasher\DefaultPasswordHasher;
  3.  
  4. class User extends Entity
  5. {
  6. // ... other methods
  7.  
  8. // Automatically hash passwords when they are changed.
  9. protected function _setPassword(string $password)
  10. {
  11. $hasher = new DefaultPasswordHasher();
  12. return $hasher->hash($password);
  13. }
  14. }

Further Reading