Multi-factor authentication (MFA) support
jasny opened this issue · 1 comments
The method of MFA shouldn't be important for this lib, though it would always include verifying some sort of code. Instead of requiring the use of wrapper, a callback that takes the user and code and returns a boolean should be all that's needed for the Auth
class.
In addition to the context, add bool $mfa
as argument for getAuthRole()
. This will be set to true
if the user is MFA authenticated. It's up to the User
class to return a role like 'mfa-required' if needed. Methods like isLoggedIn()
will still return true
, even if the login is just partial.
To logic to setup MFA (like creating an OTP secret, sending an email, etc) is outside the scope of this library.
If MFA fails the user is automatically logged out.
class AuthController extends Jasny\Controller
{
public function run(...$args)
{
try {
return parent::run(...$args);
} catch (LoginException $exception) {
$this->session->flash('warning', $exception->getMessage());
$this->redirect('/login');
}
}
public function postLogin()
{
$this->auth->login(
$this->getQueryParam('username'),
$this->getQueryParam('password'),
);
$next = $this->auth->is('mfa-required') ? '/login/mfa' : '/admin';
$this->redirect($next);
}
public function postLoginMfa()
{
$this->auth->mfa($this->getQueryParam('code'));
$this->redirect('/admin');
}
}
class User
{
/** One time password secret for multi factor authentication (MFA) */
public ?string $otpSecret = null;
public getAuthRole(?ContextInterface $context, bool $mfa)
{
if ($this->otpSecret !== null && !$mfa) {
return 'mfa-required';
}
return $this->role;
}
}
$levels = new Authz\Levels([
-1 => 'mfa-required',
1 => 'user',
20 => 'admin',
]);
$auth = (new Auth($levels, ...))
->withMfa(static function(User $user, string $code): bool {
return TOPT::create($user->otpSecret)->verify($code);
});
To be considered:
- How to deal with login events?
- Logging successful login
auth: true
for Auth middleware- TTL for partial auth