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

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

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

Prior to 3.6.0:

  1. Plugin::load('Authentication');

Configuration

Add the authentication to the middleware. See the CakePHP documentation on how to usemiddleware if you don’t know what it is or how to work with it.

Example of configuring the authentication middleware using authentication application hook:

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

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. If you’re not yet familiar with request attributes check the PSR7documentation.

Using Stateless Authenticators with other Authenticators

When using HttpBasic or HttpDigest with other authenticators, you shouldremember that these authenticators will halt the request when authenticationcredentials are missing or invalid. This is necessary as these authenticatorsmust send specific challenge headers in the response. If you want to combineHttpBasic or HttpDigest with other authenticators, you may want toconfigure these authenticators as the last authenticators:

  1. use Authentication\AuthenticationService;
  2.  
  3. // Instantiate the service
  4. $service = new AuthenticationService();
  5.  
  6. // Load identifiers
  7. $service->loadIdentifier('Authentication.Password', [
  8. 'fields' => [
  9. 'username' => 'email',
  10. 'password' => 'password'
  11. ]
  12. ]);
  13.  
  14. // Load the authenticators leaving Basic as the last one.
  15. $service->loadAuthenticator('Authentication.Session');
  16. $service->loadAuthenticator('Authentication.Form');
  17. $service->loadAuthenticator('Authentication.HttpBasic');

Authentication Component

You can use the AuthenticationComponent to access the result ofauthentication, get user identity and logout user. Load the component in yourAppController::initialize() like any other component:

  1. $this->loadComponent('Authentication.Authentication', [
  2. 'logoutRedirect' => '/users/login' // Default is false
  3. ]);

Once loaded, the AuthenticationComponent will require that all actions have anauthenticated user present, but perform no other access control checks. You candisable this check for specific actions using allowUnauthenticated():

  1. // In your controller's beforeFilter method.
  2. $this->Authentication->allowUnauthenticated(['view']);

Accessing the user / identity data

You can get the authenticated identity data using the authentication component:

  1. $user = $this->Authentication->getIdentity();

You can also get the identity directly from the request instance:

  1. $user = $request->getAttribute('identity');

Checking the login status

You can check if the authentication process was successful by accessing the resultobject:

  1. // Using Authentication component
  2. $result = $this->Authentication->getResult();
  3.  
  4. // Using request object
  5. $result = $request->getAttribute('authentication')->getResult();
  6.  
  7. if ($result->isValid()) {
  8. $user = $request->getAttribute('identity');
  9. } else {
  10. $this->log($result->getStatus());
  11. $this->log($result->getErrors());
  12. }

The result sets objects status returned from getStatus() will match one ofthese these constants in the Result object:

  • ResultInterface::SUCCESS, when successful.
  • ResultInterface::FAILURE_IDENTITY_NOT_FOUND, when identity could not be found.
  • ResultInterface::FAILURE_CREDENTIALS_INVALID, when credentials are invalid.
  • ResultInterface::FAILURE_CREDENTIALS_MISSING, when credentials are missing in the request.
  • ResultInterface::FAILURE_OTHER, on any other kind of failure.
    The error array returned by getErrors() contains additional informationcoming from the specific system against which the authentication attempt wasmade. For example LDAP or OAuth would put errors specific to theirimplementation in here for easier logging and debugging the cause. But most ofthe included authenticators don’t put anything in here.

Clearing the identity / logging the user out

To log an identity out just do:

  1. $this->Authentication->logout();

If you have set the loginRedirect config, Authentication::logout() willreturn that value else will return false. It won’t perform any actual redirectionin either case.

Alternatively, instead of the component you can also use the request instance to log out:

  1. $return = $request->getAttribute('authentication')->clearIdentity($request, $response);
  2. debug($return);

The debug will show you an array like this:

  1. [
  2. 'response' => object(Cake\Http\Response) { ... },
  3. 'request' => object(Cake\Http\ServerRequest) { ... }
  4. ]

Note

This will return an array containing the request and responseobjects. Since both are immutable you’ll get new objects back. Depending on yourcontext you’re working in you’ll have to use these instances from now on if youwant to continue to work with the modified response and request objects.

Further Reading