Наименование на проекта: BG16RFPR001-1.001-0325-C01
Реализирана е двуфакторна автентификация чрез Google Authenticator, базирана на TOTP алгоритъм с временни 6-цифрени кодове. Потребителите могат да активират и деактивират този метод от профила си, като при първоначална настройка се генерира секретен ключ и QR код за сканиране с мобилно приложение. При логин, след успешна проверка на потребителско име и парола, системата изисква допълнителен код от Google Authenticator. Поддържа се избор между различни 2FA методи, доверени устройства и защита срещу повторна употреба и времеви атаки, което значително повишава нивото на сигурност на акаунтите.
Системата поддържа двуфакторна автентификация чрез Google Authenticator (TOTP - Time-based One-Time Password). Това е алтернатива на email-based 2FA, която използва мобилно приложение за генериране на временни кодове. Google Authenticator е по-удобен и по-безопасен метод, тъй като не зависи от имейл доставката и работи офлайн.
Google Authenticator е мобилно приложение, което генерира временни 6-цифрени кодове (TOTP) за двуфакторна автентификация. Кодовете се обновяват на всеки 30 секунди и са уникални за всеки акаунт.
Офлайн работа:
По-висока сигурност:
Удобство:
SchebTwoFactorBundle
scheb/2fa-google-authenticator
endroid/qr-code
BaseUser Entity
TotpInterface (за Google Authenticator)TwoFactorCondition
isEnableTwoFa флагаВече инсталирани пакети:
{
"scheb/2fa-bundle": "^7.5",
"scheb/2fa-google-authenticator": "^7.5",
"endroid/qr-code": "^5.1"
}
config/packages/scheb_two_factor.yaml)Текуща конфигурация (само email):
scheb_two_factor:
trusted_device:
enabled: true
email:
enabled: true
digits: 6
mailer: App\Mailer\TwoFactorMailer
sender_email: '%env(NO_REPLY_MAIL)%'
sender_name: No-Reply
template: security/2fa_form.html.twig
security_tokens:
- PostAuthenticationToken
two_factor_condition: App\Service\Core\TwoFactorCondition
Добавяне на Google Authenticator конфигурация:
scheb_two_factor:
trusted_device:
enabled: true
# Email 2FA (съществуваща)
email:
enabled: true
digits: 6
mailer: App\Mailer\TwoFactorMailer
sender_email: '%env(NO_REPLY_MAIL)%'
sender_name: No-Reply
template: security/2fa_form.html.twig
# Google Authenticator 2FA (нова)
google:
enabled: true
server_name: '%env(SITE_NAME)%'
issuer: '%env(SITE_NAME)%'
template: security/2fa_google_form.html.twig
digits: 6
window: 1
security_tokens:
- PostAuthenticationToken
two_factor_condition: App\Service\Core\TwoFactorCondition
Параметри:
google.enabled: true - Активира Google Authenticator поддръжкаgoogle.server_name - Име на сървъра (показва се в приложението)google.issuer - Издател на токена (показва се в приложението)google.template - Twig шаблон за форматаgoogle.digits: 6 - Дължина на кода (6 цифри)google.window: 1 - Допустимо отклонение във времето (±30 секунди)Добавяне на TOTP поддръжка:
<?php
namespace App\Entity\User;
use Scheb\TwoFactorBundle\Model\Totp\TotpConfiguration;
use Scheb\TwoFactorBundle\Model\Totp\TotpConfigurationInterface;
use Scheb\TwoFactorBundle\Model\Totp\TwoFactorInterface as TotpTwoFactorInterface;
class BaseUser implements
PasswordAuthenticatedUserInterface,
TwoFactorInterface, // За email 2FA
TotpTwoFactorInterface // За Google Authenticator
{
// Съществуващи полета...
#[ORM\Column(nullable: true)]
protected ?string $totpSecret = null;
#[ORM\Column(nullable: true)]
protected ?string $twoFactorMethod = null; // 'email' или 'google'
// Методи за TOTP
public function isTotpAuthenticationEnabled(): bool
{
return $this->getIsEnableTwoFa() && $this->twoFactorMethod === 'google';
}
public function getTotpAuthenticationUsername(): string
{
return $this->email;
}
public function getTotpConfiguration(): ?TotpConfigurationInterface
{
if (!$this->totpSecret) {
return null;
}
return new TotpConfiguration(
$this->totpSecret,
TotpConfiguration::ALGORITHM_SHA1,
30, // Period (30 секунди)
6 // Digits (6 цифри)
);
}
public function setTotpSecret(?string $totpSecret): self
{
$this->totpSecret = $totpSecret;
return $this;
}
public function getTotpSecret(): ?string
{
return $this->totpSecret;
}
public function setTwoFactorMethod(?string $twoFactorMethod): self
{
$this->twoFactorMethod = $twoFactorMethod;
return $this;
}
public function getTwoFactorMethod(): ?string
{
return $this->twoFactorMethod;
}
}
Контролер за активиране на Google Authenticator:
<?php
namespace App\Controller\User;
use App\Entity\User\BaseUser;
use Doctrine\ORM\EntityManagerInterface;
use Scheb\TwoFactorBundle\Security\TwoFactor\Provider\Totp\TotpAuthenticatorInterface;
use Bundle\FrameworkBundle\Controller\AbstractController;
use Request;
use Response;
use Route;
use IsGranted;
use Endroid\QrCode\Builder\Builder;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelHigh;
use Endroid\QrCode\Writer\PngWriter;
class TwoFactorSetupController extends AbstractController
{
public function __construct(
private readonly TotpAuthenticatorInterface $totpAuthenticator,
private readonly EntityManagerInterface $entityManager
) {
}
#[Route('/2fa/setup/google', name: '2fa_setup_google')]
#[IsGranted('ROLE_USER')]
public function setupGoogle(Request $request): Response
{
/** @var BaseUser $user */
$user = $this->getUser();
// Генериране на нов secret, ако няма такъв
if (!$user->getTotpSecret()) {
$secret = $this->totpAuthenticator->generateSecret();
$user->setTotpSecret($secret);
$this->entityManager->flush();
}
// Генериране на QR код
$qrCodeContent = $this->totpAuthenticator->getQRContent($user);
$qrCode = Builder::create()
->writer(new PngWriter())
->data($qrCodeContent)
->encoding(new Encoding('UTF-8'))
->errorCorrectionLevel(new ErrorCorrectionLevelHigh())
->size(300)
->margin(10)
->build();
// Валидация на кода (ако е изпратена форма)
if ($request->isMethod('POST')) {
$code = $request->request->get('code');
if ($this->totpAuthenticator->checkCode($user, $code)) {
// Кодът е валиден - активиране на 2FA
$user->setIsEnableTwoFa(true);
$user->setTwoFactorMethod('google');
$this->entityManager->flush();
$this->addFlash('success', 'Google Authenticator е активиран успешно!');
return $this->redirectToRoute('app_account');
} else {
$this->addFlash('error', 'Невалиден код. Моля, опитайте отново.');
}
}
return $this->render('user/2fa_setup_google.html.twig', [
'qrCode' => $qrCode->getDataUri(),
'secret' => $user->getTotpSecret(),
]);
}
#[Route('/2fa/disable/google', name: '2fa_disable_google')]
#[IsGranted('ROLE_USER')]
public function disableGoogle(): Response
{
/** @var BaseUser $user */
$user = $this->getUser();
$user->setIsEnableTwoFa(false);
$user->setTwoFactorMethod(null);
$user->setTotpSecret(null);
$this->entityManager->flush();
$this->addFlash('success', 'Google Authenticator е деактивиран.');
return $this->redirectToRoute('app_account');
}
}
templates/user/2fa_setup_google.html.twig:
{% extends 'base.html.twig' %}
{% block title %}Настройка на Google Authenticator{% endblock %}
{% block body %}
<div class="container">
<div class="row justify-content-center">
<div class="col-md-6">
<div class="card">
<div class="card-header">
<h3>Настройка на Google Authenticator</h3>
</div>
<div class="card-body">
<ol>
<li>Инсталирайте Google Authenticator на вашето мобилно устройство</li>
<li>Сканирайте QR кода по-долу или въведете secret ключа ръчно</li>
<li>Въведете 6-цифрения код от приложението за потвърждение</li>
</ol>
<div class="text-center my-4">
<img src="{{ qrCode }}" alt="QR Code" class="img-fluid">
</div>
<div class="alert alert-info">
<strong>Secret ключ:</strong> {{ secret }}
<br><small>Използвайте този ключ, ако не можете да сканирате QR кода</small>
</div>
<form method="post">
<div class="mb-3">
<label for="code" class="form-label">Въведете код от Google Authenticator</label>
<input
type="text"
id="code"
name="code"
class="form-control"
maxlength="6"
pattern="[0-9]{6}"
required
autofocus
inputmode="numeric"
>
</div>
<input type="hidden" name="_token" value="{{ csrf_token('2fa_setup') }}">
<div class="d-grid gap-2">
<button type="submit" class="btn btn-primary">Активирай Google Authenticator</button>
<a href="{{ path('app_account') }}" class="btn btn-secondary">Отказ</a>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
templates/security/2fa_google_form.html.twig:
{% extends 'login-layout.html.twig' %}
{% block body %}
<form class="form" action="{{ checkPathUrl ? checkPathUrl: path(checkPathRoute) }}" method="post" data-enter-submit-id="_submit">
<div class="edit-container-box-body">
{% if authenticationError %}
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
<i class="ri-close-circle-line me-1"></i>
{{ authenticationError|dtrans(authenticationErrorData, 'SchebTwoFactorBundle') }}
</div>
{% endif %}
<p class="text-info">
<strong>Въведете код от Google Authenticator</strong>
</p>
<div class="mb-3">
<label for="_auth_code">Authentication code:</label>
<input
id="_auth_code"
class="form-control ds-form-control"
type="text"
name="{{ authCodeParameterName }}"
autocomplete="one-time-code"
autofocus
maxlength="6"
pattern="[0-9]{6}"
inputmode="numeric"
required
/>
</div>
<div class="mb-3">
{% if displayTrustedOption %}
<p class="widget">
<label for="_trusted">
<input id="_trusted" type="checkbox" name="{{ trustedParameterName }}"/>
{{ "trusted"|dtrans({}, 'SchebTwoFactorBundle') }}
</label>
</p>
{% endif %}
{% if isCsrfProtectionEnabled %}
<input type="hidden" name="{{ csrfParameterName }}" value="{{ csrf_token(csrfTokenId) }}">
{% endif %}
</div>
<div class="form-group ds-form-group text-center">
<button type="submit" id="_submit" name="_submit" value="{{ "login"|dtrans({}, 'SchebTwoFactorBundle') }}" class="btn btn-primary w-100">
{{ 'login.loginBtnTitle'|dtrans }}
</button>
</div>
<p class="cancel mt-3 mb-0 text-center">
<a href="{{ logoutPath }}">{{ "cancel"|dtrans({}, 'SchebTwoFactorBundle') }}</a>
</p>
</div>
</form>
{% endblock %}
Поддръжка на различни методи:
<?php
namespace App\Service\Core;
use App\Entity\User\BaseUser;
use Scheb\TwoFactorBundle\Security\TwoFactor\AuthenticationContextInterface;
use Scheb\TwoFactorBundle\Security\TwoFactor\Condition\TwoFactorConditionInterface;
class TwoFactorCondition implements TwoFactorConditionInterface
{
public function shouldPerformTwoFactorAuthentication(AuthenticationContextInterface $context): bool
{
/** @var BaseUser $user */
$user = $context->getUser();
if (!$user->getIsEnableTwoFa()) {
return false;
}
// Проверява дали потребителят има конфигуриран метод
$method = $user->getTwoFactorMethod();
if ($method === 'google') {
// Проверява дали има TOTP secret
return $user->getTotpSecret() !== null;
} elseif ($method === 'email') {
// Email 2FA винаги е наличен
return true;
}
// По подразбиране използва email
return true;
}
}
Потребителят посещава страницата за настройка:
GET /2fa/setup/googleTwoFactorSetupController::setupGoogle()Генериране на TOTP Secret:
BaseUser.totpSecretГенериране на QR код:
otpauth://totp/{issuer}:{username}?secret={secret}&issuer={issuer}endroid/qr-codeПоказване на QR код:
Верификация:
TotpAuthenticatorInterface::checkCode()Потребител се логва с email и парола:
TwoFactorCondition проверява дали е необходима 2FAПроверка на метода:
twoFactorMethod === 'google', използва се Google AuthenticatortwoFactorMethod === 'email', използва се email 2FAПоказване на формата:
GET /2fasecurity/2fa_google_form.html.twigВалидация на кода:
POST /2fa_checkУспешна автентификация:
PostAuthenticationTokenГенериране на код:
Валидация:
Window (толеранс):
scheb_two_factor.yamlTOTP Secret:
HMAC-SHA1:
Времева валидност:
Brute Force:
Replay атаки:
Secret компрометиране:
| Характеристика | Email 2FA | Google Authenticator |
|---|---|---|
| Зависимост от мрежа | Да (имейл доставка) | Не (офлайн) |
| Скорост | Бавна (чакане на имейл) | Моментална |
| Сигурност | Добра | По-добра |
| Удобство | Средно | Високо |
| Настройка | Лесна | Изисква мобилно приложение |
| Валидност на код | Няколко минути | 30 секунди |
config/packages/scheb_two_factor.yaml - Конфигурация на 2FA (трябва да се добави google секция)src/Controller/User/TwoFactorSetupController.php - Контролер за настройка (трябва да се създаде)src/Entity/User/BaseUser.php - Трябва да се добави TOTP поддръжкаtemplates/user/2fa_setup_google.html.twig - Страница за настройка (трябва да се създаде)templates/security/2fa_google_form.html.twig - Форма за въвеждане на код (трябва да се създаде)src/Service/Core/TwoFactorCondition.php - Трябва да се обнови за поддръжка на различни методиscheb/2fa-google-authenticator - Вече инсталиранendroid/qr-code - Вече инсталиранДобавяне на нови полета:
// Migration
public function up(Schema $schema): void
{
$this->addSql('ALTER TABLE base_user ADD totp_secret VARCHAR(255) DEFAULT NULL');
$this->addSql('ALTER TABLE base_user ADD two_factor_method VARCHAR(50) DEFAULT NULL');
}
1. Потребител → GET /2fa/setup/google
2. TwoFactorSetupController → Генерира TOTP secret
3. TwoFactorSetupController → Генерира QR код
4. Потребител → Сканира QR код с Google Authenticator
5. Потребител → Въвежда код от приложението
6. TwoFactorSetupController → Валидира код
7. Ако валиден:
a. Активира 2FA (isEnableTwoFa = true)
b. Задава метод (twoFactorMethod = 'google')
c. Потребител → GET /login
8. Потребител → POST /login (email + password)
9. Security → Успешна автентификация
10. TwoFactorCondition → Проверява метод (google)
11. Security → Redirect към /2fa
12. Потребител → GET /2fa (показва Google Authenticator форма)
13. Потребител → Въвежда код от Google Authenticator
14. Потребител → POST /2fa_check (код)
15. SchebTwoFactorBundle → Валидира TOTP код
16. Ако валиден:
a. Създава PostAuthenticationToken
b. Redirect към /login/success
c. Потребител → Dashboard
Съвместимост:
Резервни кодове:
Множество устройства:
Миграция от Email към Google Authenticator:
Google Authenticator предоставя по-удобен и сигурен метод за 2FA в сравнение с email-based подхода. Интеграцията изисква допълнителна конфигурация и код, но предоставя значителни предимства за потребителите. Системата може да поддържа и двата метода едновременно, позволявайки на потребителите да избират предпочитания метод.