Quick Start
Install the plugin with composer from your CakePHPProject’s ROOT directory (where the composer.json file is located)
- php composer.phar require cakephp/authentication
Load the plugin by adding the following statement in your project’s src/Application.php
:
- public function bootstrap()
- {
- parent::bootstrap();
- $this->addPlugin('Authentication');
- }
Prior to 3.6.0:
- 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:
- use Authentication\AuthenticationService;
- use Authentication\AuthenticationServiceProviderInterface;
- use Authentication\Middleware\AuthenticationMiddleware;
- use Psr\Http\Message\ResponseInterface;
- use Psr\Http\Message\ServerRequestInterface;
- class Application extends BaseApplication implements AuthenticationServiceProviderInterface
- {
- /**
- * Returns a service provider instance.
- *
- * @param \Psr\Http\Message\ServerRequestInterface $request Request
- * @param \Psr\Http\Message\ResponseInterface $response Response
- * @return \Authentication\AuthenticationServiceInterface
- */
- public function getAuthenticationService(ServerRequestInterface $request, ResponseInterface $response)
- {
- $service = new AuthenticationService();
- $fields = [
- 'username' => 'email',
- 'password' => 'password'
- ];
- // Load identifiers
- $service->loadIdentifier('Authentication.Password', compact('fields'));
- // Load the authenticators, you want session first
- $service->loadAuthenticator('Authentication.Session');
- $service->loadAuthenticator('Authentication.Form', [
- 'fields' => $fields,
- 'loginUrl' => '/users/login'
- ]);
- return $service;
- }
- public function middleware($middlewareQueue)
- {
- // Various other middlewares for error handling, routing etc. added here.
- // Add the authentication middleware
- $authentication = new AuthenticationMiddleware($this);
- // Add the middleware to the middleware queue
- $middlewareQueue->add($authentication);
- return $middlewareQueue;
- }
- }
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:
- use Authentication\AuthenticationService;
- // Instantiate the service
- $service = new AuthenticationService();
- // Load identifiers
- $service->loadIdentifier('Authentication.Password', [
- 'fields' => [
- 'username' => 'email',
- 'password' => 'password'
- ]
- ]);
- // Load the authenticators leaving Basic as the last one.
- $service->loadAuthenticator('Authentication.Session');
- $service->loadAuthenticator('Authentication.Form');
- $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:
- $this->loadComponent('Authentication.Authentication', [
- 'logoutRedirect' => '/users/login' // Default is false
- ]);
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()
:
- // In your controller's beforeFilter method.
- $this->Authentication->allowUnauthenticated(['view']);
Accessing the user / identity data
You can get the authenticated identity data using the authentication component:
- $user = $this->Authentication->getIdentity();
You can also get the identity directly from the request instance:
- $user = $request->getAttribute('identity');
Checking the login status
You can check if the authentication process was successful by accessing the resultobject:
- // Using Authentication component
- $result = $this->Authentication->getResult();
- // Using request object
- $result = $request->getAttribute('authentication')->getResult();
- if ($result->isValid()) {
- $user = $request->getAttribute('identity');
- } else {
- $this->log($result->getStatus());
- $this->log($result->getErrors());
- }
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 bygetErrors()
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:
- $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:
- $return = $request->getAttribute('authentication')->clearIdentity($request, $response);
- debug($return);
The debug will show you an array like this:
- [
- 'response' => object(Cake\Http\Response) { ... },
- 'request' => object(Cake\Http\ServerRequest) { ... }
- ]
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.