dakataa / 2fa
Symfony Security Two Factor Authenticator (2FA)
Requires
- php: >=8.1
- ramsey/uuid: ^4.7
- spomky-labs/otphp: ^11.3
- symfony/framework-bundle: ^7.0
- symfony/messenger: ^7.0
- symfony/security-bundle: ^7.0
Requires (Dev)
- phpunit/phpunit: ^10.5 || ^11.5
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
This package helps you to enable Two Factor Authenticator for users over your current authenticator. Providing SMS, Email and OTP (TOTP / HOTP). Easy way to implement Custom Auth Code provider.
To get started, install the bundle:
composer require dakataa/2fa
Primary authenticators (since 1.1.0)
Passports with PasswordCredentials automatically enter 2FA when the bundle is
enabled and the user has an active second factor. Other primary authenticators,
such as Passkey or OAuth, opt in with TwoFactorBadge after verifying their
primary credentials:
use Dakataa\Security\TwoFactorAuthenticator\Authentication\Badge\TwoFactorBadge; use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge; use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport; return new SelfValidatingPassport( new UserBadge($user->getUserIdentifier(), fn() => $user), [new TwoFactorBadge()], );
The listener replaces the authenticated token with TwoFactorAuthenticationToken
and supplies the challenge on LoginSuccessEvent. Do not add this badge to
access-token authentication or to the programmatic login that completes 2FA.
The badge requests the user's configured second factor; it does not verify the
primary credentials itself.
Default response handling
No additional success handler configuration is required for the default flow.
Keep your existing success handler and, for primary authenticators without
PasswordCredentials, add TwoFactorBadge as shown above.
Symfony invokes the authenticator's success handler first. When 2FA is pending,
the bundle's LoginSuccessEvent listener replaces its response with a JSON
challenge or a redirect to the code form. After successful code verification,
the bundle logs the user in through the configured firewall; the normal
success response is then returned.
Response replacement does not undo work performed by the success handler. A JWT constructed only for the original response is discarded, but database updates, notifications, or other side effects have already happened. An exception thrown by the handler can also prevent the challenge from being generated. Use the optional wrapper below when the handler itself must wait until authentication is complete.
Optional success handler wrapper (since 1.1.0)
TwoFactorAuthenticationSuccessHandler skips the application success handler
while 2FA is pending. The listener replaces its placeholder response with the
same challenge or form redirect. With a normal token, the wrapper delegates
unchanged to the application handler.
Register the wrapper explicitly with your application handler; the bundle does not register it automatically because each application chooses its own delegate:
# config/services.yaml services: Dakataa\Security\TwoFactorAuthenticator\Authentication\TwoFactorAuthenticationSuccessHandler: arguments: $handler: '@App\Security\AuthenticationHandler'
App\Security\AuthenticationHandler is an example service implementing Symfony's
AuthenticationSuccessHandlerInterface. It contains your normal success logic
and does not need a 2FA token check.
For password login, configure the wrapper as the success handler:
# config/packages/security.yaml (merge into your existing firewall) security: firewalls: main: json_login: check_path: auth_login success_handler: Dakataa\Security\TwoFactorAuthenticator\Authentication\TwoFactorAuthenticationSuccessHandler
For form_login, use the same success_handler setting under form_login
instead. Keep your existing login path, provider, and other firewall options.
For a custom authenticator, inject the wrapper as the success handler and delegate to it:
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface; // Inside your authenticator; add any other dependencies to this constructor. public function __construct(private readonly AuthenticationSuccessHandlerInterface $successHandler) { } public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response { return $this->successHandler->onAuthenticationSuccess($request, $token); }
# config/services.yaml services: App\Security\PasskeyAuthenticator: arguments: $successHandler: '@Dakataa\Security\TwoFactorAuthenticator\Authentication\TwoFactorAuthenticationSuccessHandler'
Failure handling stays with your existing failure handler. If an authenticator previously injected one service for both success and failure handling, inject the success wrapper separately; it implements only the success handler contract.
When choosing this wrapper, apply its wiring to every primary login whose
success handler must wait for completed authentication. Adding
TwoFactorBadge selects the 2FA policy, but does not intercept a custom success
handler. Do not issue tokens or perform final login side effects directly in
the authenticator before delegating. The configured firewall used to complete
2FA must retain its normal success handler through this wrapper: once the
second factor is verified, a normal token passes through to the delegate.
JSON challenges
JSON challenge responses include the verified identifier, even when the primary request did not contain a username:
{
"username": "user@example.com",
"challenge": {
"type": "otp",
"url": "https://example.com/2fa/check",
"required_fields": ["username", "code"]
}
}
The response key username is fixed. Send its value using the configured
username_parameter when submitting a stateless code check; required_fields
uses the configured request field names. With an existing started session, the
code check obtains the username from the session instead.
Tests
composer install
composer test
Configuration:
### config/packages/dakataa_2fa.yaml dakataa_two_factor_authenticator: enabled: true firewall: main code_parameter: code username_parameter: username form_path: auth_2fa_form check_path: auth_2fa_check target: parameter: _target path_default: /
Create Controller to handle form & check paths
<?php // .... #[Route('/2fa')] class TwoFactorController extends AbstractController { #[Route('/form', name: 'auth_2fa_form')] public function form(AuthenticationUtils $authenticationUtils): Response { return $this->render('auth/2fa/form.html.twig', [ 'error' => $authenticationUtils->getLastAuthenticationError(), ]); } #[Route('/check', name: 'auth_2fa_check')] public function check(): Response { throw new Exception('Please setup 2FA key "check_path" in configuration.'); } #[IsGranted('ROLE_USER')] #[Route('/setup/{authenticator}', name: "auth_2fa_setup")] public function setup(#[CurrentUser] UserInterface $user, TwoFactorAuthenticatorProvider $twoFactorAuthenticatorProvider, string $authenticator = null): Response { if($authenticator) { $entity = $twoFactorAuthenticatorProvider->setupProvider($user, $authenticator); $twoFactorAuthenticatorProvider->getAuthenticator($user)?->dispatch($entity); return match($authenticator) { 'otp' => $this->render('auth/2fa/setup_otp.html.twig', [ 'parameters' => $entity->getTwoFactorParameters() ]), default => new RedirectResponse($this->generateUrl('auth_2fa_form')) }; } return $this->render('auth/2fa/setup.html.twig'); } }
Views
auth/2fa/form.html.twig
{% extends 'base.html.twig' %}
{% block body %}
<h3>2FA</h3>
{% if error %}
<div>{{ error.message|trans(error.messageData, 'security') }}</div>
{% endif %}
<p>Please provide code you receive.</p>
<form method="POST" action="{{ url('auth_2fa_check') }}">
<label>
Code
<input type="text" name="code" />
</label>
<button type="submit">Submit</button>
</form>
{% endblock %}
auth/2fa/setup.html.twig
{% extends 'base.html.twig' %}
{% block body %}
<h3>Select 2FA Authenticator</h3>
<ul>
<li>
<a href="{{ url('auth_2fa_setup', { authenticator: 'otp' }) }}">OTP Authenticator (Google Auth, etc.)</a>
</li>
<li>
<a href="{{ url('auth_2fa_setup', { authenticator: 'sms' }) }}">SMS</a>
</li>
<li>
<a href="{{ url('auth_2fa_setup', { authenticator: 'email' }) }}">Email</a>
</li>
</ul>
{% endblock %}
auth/2fa/setup_otp.html.twig
{% extends 'base.html.twig' %}
{% block body %}
<h3>OTP</h3>
<div>
<strong>Secret:</strong>
<code>
{{ parameters.secret }}
</code>
<p>
<strong>Barcode:</strong>
You have to generate BARCODE
contains this value {{ parameters.provisioningUri }}
</p>
</div>
<a href="{{ url('auth_2fa_form') }}">Activate</a>
{% endblock %}
Setup Event Handlers
Example with temporary cache storage. We should store Two Factor User information in current cache storage. Right way is to store it in database user table or separate table related to user.
<?php // ... class TwoFactorEventHandler { public function __construct(private readonly CacheItemPoolInterface $twoFactorTemporaryStorage) { } #[AsEventListener(event: TwoFactorEntityInvokingEvent::class)] public function onTwoFactorEntityInvokingEvent(TwoFactorEntityInvokingEvent $event): void { $user = $event->getUser(); $cacheKey = sha1($user->getUserIdentifier()); if(!$this->twoFactorTemporaryStorage->hasItem($cacheKey)) { return; } $data = $this->twoFactorTemporaryStorage->getItem($cacheKey)->get(); if(empty($data) || !is_array($data)) { return; } [ 'authenticator' => $authenticator, 'parameters' => $parameters, 'active' => $active ] = $data + [ 'authenticator' => null, 'parameters' => null, 'active' => false ]; if(!$authenticator) { return; } $entity = new TwoFactorAuthenticatorEntity($user->getUserIdentifier(), $authenticator, $parameters, $active); $event->setEntity($entity); } #[AsEventListener(event: TwoFactorSetupEvent::class)] public function onTwoFactorSetupEvent(TwoFactorSetupEvent $event): void { $cacheKey = sha1($event->getUser()->getUserIdentifier()); $cacheItem = $this->twoFactorTemporaryStorage->getItem($cacheKey); $cacheItem->set([ 'authenticator' => $event->getEntity()->getTwoFactorAuthenticator(), 'parameters' => $event->getEntity()->getTwoFactorParameters(), 'active' => false ]); $this->twoFactorTemporaryStorage->save($cacheItem); } #[AsEventListener(event: TwoFactorActivateEvent::class)] public function onTwoFactorActivateEvent(TwoFactorActivateEvent $event): void { $cacheKey = sha1($event->getUser()->getUserIdentifier()); $cacheItem = $this->twoFactorTemporaryStorage->getItem($cacheKey); if(empty($data = $cacheItem->get())) { return; } $data = [...$data, 'active' => true]; $cacheItem->set($data); $this->twoFactorTemporaryStorage->save($cacheItem); $event->setResponse(new RedirectResponse('/')); } }
Events
| Event | Description |
|---|---|
| TwoFactorEntityInvokingEvent::class | This event is triggered when bundle need information about user 2FA. You have to Provide TwoFactorAuthenticatorEntity object containing authenticator information. |
| TwoFactorSetupEvent::class | This event is triggered on user authenticator 2FA setup. You receive authenticator parameters for the user and you have to save it for future use. |
| TwoFactorActivateEvent::class | This event is triggered after successful 2FA code validation on SETUP. |
Messages
This bundle use Symfony Messenger. We have two notifications which you have to handle.
| Notification | Description |
|---|---|
| SmsNotification::class | Contains Auth Code |
| EmailNotification::class | Contains Auth Code |
How to handle notifications
<?php namespace App\Component\MessageHandler; use Dakataa\Security\TwoFactorAuthenticator\Notification\EmailNotification; use Dakataa\Security\TwoFactorAuthenticator\Notification\SmsNotification; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\Messenger\Attribute\AsMessageHandler; class TwoFactorMessageHandler extends AbstractController { #[AsMessageHandler] public function smsNotificationHandler(SmsNotification $message) { // Send SMS with code // $message->getCode(); } #[AsMessageHandler] public function emailNotificationHandler(EmailNotification $message) { // Send Email with code // $message->getCode(); } }