This plugin provides two factor authentication functionality using RobThree/TwoFactorAuth library.
Basically, it works similar way CakePHP FormAuthenticate
does. After submitting correct username/password, if the user has secret
field set, he will be asked to enter a one-time code.
Attention: it only provides authenticate provider and component and does not take care of users signup, management etc.
- CakePHP 3.0+
You can install this plugin into your CakePHP application using Composer.
composer require andrej-griniuk/cakephp-two-factor-auth
First of all you need to add secret
field to your users table (field name can be changed to TwoFactorAuth.Form
authenticator configuration).
ALTER TABLE `users` ADD `secret` VARCHAR(255) NULL;
Second, you need to load the plugin in your bootstrap.php
Plugin::load('TwoFactorAuth', ['bootstrap' => true, 'routes' => true]);
You can see the default config values here and find out what do they mean here. To overwrite them, create two_factor_auth.php file in your config
directory.
Then you need to set up authentication in your controller as you would normally do, but using TwoFactorAuth.Auth
component and TwoFactorAuth.Form
authenticator, e.g.:
class AppController extends Controller
{
public function initialize()
{
parent::initialize();
$this->loadComponent('Flash');
$this->loadComponent('Security');
$this->loadComponent('Csrf');
$this->loadComponent('TwoFactorAuth.Auth', [
'authenticate' => ['TwoFactorAuth.Form'],
]);
}
}
Basically, it works same way CakePHP Form
authenticator does.
After entering correct username/password combination, if the user has secret
field (can be overwritten via TwoFactorAuth.Form
configuration) set he will be redirected to verifyAction
(by default ['controller' => 'TwoFactorAuth', 'action' => 'verify', 'plugin' => 'TwoFactorAuth', 'prefix' => false]
) where he is asked to enter a one-time code.
There is no logic behind the action, it only renders the form that has to be submitted to the loginAction
again with code
field set.
You can override the view using standard CakePHP conventions to override Plugin views or change the verifyAction
in TwoFactorAuth
configuration.
You can access the RobThree\Auth\TwoFactorAuth instance from your controller via $this->Auth->tfa
. For example, you can generate user's secret and get QR code data URI for it this way:
$secret = $this->Auth->tfa->createSecret();
$secretDataUri = $this->Auth->tfa->getQRCodeImageAsDataUri('Andrej Griniuk', $secret);
Then display it in your view:
<img src="<?= $secretDataUri ?>" />
See the library page for full documentation: https://github.com/RobThree/TwoFactorAuth
https://github.com/andrej-griniuk/cakephp-two-factor-auth/issues
https://github.com/RobThree/TwoFactorAuth
Copyright (c) 2016, Andrej Griniuk and licensed under The MIT License.