Описание
Плагин «Two-Factor» обеспечивает дополнительный уровень безопасности при входе в систему WordPress, требуя от пользователей ввода второго средства аутентификации в дополнение к паролю. Это помогает защитить систему от несанкционированного доступа даже в случае утечки паролей.
Инструкции по установке
Важно: Каждый пользователь должен самостоятельно настроить параметры двухфакторной аутентификации.
Для частных пользователей
- Перейти в свой профиль: В админ-панели WordPress перейдите в раздел «Пользователи» «Профиль»
- Найти настройки Two-Factor: Прокрутите страницу вниз до раздела «Настройки двухфакторной аутентификации»
- Choose your methods: Enable one or more authentication providers (noting a site admin may have hidden one or more so what is available could vary):
- Приложение-аутентификатор (TOTP) — Используйте такие приложения, как Google Authenticator, Authy или 1Password
- Email коды — Получайте одноразовые коды по email
- Резервные коды — Сгенерируйте одноразовые резервные коды на случай чрезвычайных ситуаций
- Фиктивный метод — Исключительно для тестирования (требует WP_DEBUG)
- Настроить все методы: Следуйте инструкциям по настройке для каждого включенного поставщика
- Установить основной метод: Выберите метод, который будет использоваться в качестве метода аутентификации по умолчанию
- Сохранить изменения: Нажмите «Обновить профиль», чтобы сохранить свои настройки
Для администраторов сайтов
- Настройки плагина: Плагин имеет страницу настроек в разделе «Настройки Two-Factor», на которой можно отключить определённых провайдеров на всём сайте.
- Управление пользователями: Администраторы могут настроить двухфакторную аутентификацию для других пользователей, отредактировав их профили
- Советы по безопасности: Рекомендуйте пользователям включать резервные методы, чтобы предотвратить блокировку учетных записей
Доступные методы аутентификации
Приложение-аутентификатор (TOTP) — рекомендуется
- Безопасность: Высокая — одноразовые пароли, зависимые от времени
- Настройка: Отсканируйте QR-код с помощью приложения-аутентификатора
- Совместимость: Работает с Google Authenticator, Authy, 1Password и другими TOTP приложениями
- Оптимально для: Большинства пользователей, обеспечивает отличную безопасность и удобен в использовании
Резервные коды — рекомендуется
- Безопасность: Средняя — одноразовые коды
- Настройка: Создайте 10 резервных кодов для доступа в экстренных случаях
- Совместимость: Работает везде, не требует специального оборудования
- Оптимально для: Экстренный доступ в случаях, когда другие способы недоступны
Коды электронной почты
- Безопасность: Средняя — одноразовые коды, отправляемые по email
- Настройка: Автоматическая — используется ваш email адрес WordPress
- Совместимость: Работает с любым устройством, поддерживающим email
- Оптимально для: Пользователей, предпочитающих email-аутентификацию
Ключи безопасности FIDO U2F
- Устарело и удалено в связи с прекращением поддержки со стороны браузеров.
Фиктивный метод
- Безопасность: Отсутствует — всегда завершается успешно
- Настройки: Доступно только при включенном параметре WP_DEBUG
- Цель: Исключительно для тестирования и разработки
- Оптимально для: Разработчиков, тестирующих плагин
Важные примечания
Требование HTTPS
- Все методы работают как на сайтах с HTTP, так и HTTPS
Совместимость с браузерами
- Методы TOTP и email работают на всех устройствах и во всех браузерах
Восстановление учётной записи
- Всегда включайте резервные коды, чтобы избежать блокировки доступа к вашей учетной записи
- Если у вас пропал доступ ко всем способам аутентификации, обратитесь к администратору сайта
Лучшие практики безопасности
- По возможности используйте несколько методов аутентификации
- Храните резервные коды в надёжном месте
- Регулярно проверяйте и обновляйте свои настройки аутентификации
Для получения дополнительной информации о двухфакторной аутентификации в WordPress ознакомьтесь с Руководством по расширенной безопасности администрирования WordPress.
Подробную историю можно посмотреть в этом посте.
События и фильтры
Вот список хуков событий и фильтров, предоставляемых плагином:
- Фильтр
two_factor_providersпереопределяет доступных поставщиков двухфакторной аутентификации, таких как email и одноразовые пароли на основе времени. Значения массива – это названия PHP классов поставщиков двухфакторной аутентификации. two_factor_providers_for_userfilter overrides the available two-factor providers for a specific user. Array values are instances of provider classes and the user objectWP_Useris available as the second argument.- Фильтр
two_factor_enabled_providers_for_userпереопределяет список поставщиков двухфакторной аутентификации, включенных для пользователя. Первый аргумент – это массив включенных имен классов поставщиков в виде значений, второй аргумент – это идентификатор пользователя. two_factor_is_required_for_userfilter controls whether two-factor authentication is required for a user. Returnfalseto bypass the two-factor flow (e.g. for trusted IP addresses). First argument is a boolean (whether the user has a primary provider configured), the second argument is theWP_Userobject.two_factor_fallback_provider_for_userfilter overrides the provider forced on when none of a user’s stored two-factor providers are still registered (e.g. after a provider plugin is deactivated). Defaults toTwo_Factor_Email. First argument is the provider classname, the second is the user ID, the third is the array of provider classnames that were stored for the user but are no longer registered. The returned provider must be registered and available to the user (is_available_for_user()), or the user is shown an error instead of being let through with a fallback.- Событие
two_factor_user_authenticatedполучает авторизованныйWP_Userобъект в качестве первого аргумента для определения вошедшего в систему пользователя сразу после рабочего процесса аутентификации. two_factor_user_api_login_enablefilter restricts authentication for REST API and XML-RPC to application passwords only. Provides the user ID as the second argument.two_factor_email_token_ttlfilter overrides the time interval in seconds that an email token is considered after generation. Accepts the time in seconds as the first argument and the ID of theWP_Userobject being authenticated.- Фильтр
two_factor_email_token_lengthпереопределяет значение по умолчанию, равное 8 символам, для токенов, отправляемых по электронной почте. two_factor_backup_code_lengthfilter overrides the default 8 character count for backup codes. Provides theWP_Userof the associated user as the second argument.two_factor_rest_api_can_edit_userfilter overrides whether a user’s Two-Factor settings can be edited via the REST API. First argument is the current$can_editboolean, the second argument is the user ID.two_factor_before_authentication_promptaction which receives the provider object and fires prior to the prompt shown on the authentication input form.two_factor_after_authentication_promptaction which receives the provider object and fires after the prompt shown on the authentication input form.two_factor_after_authentication_inputaction which receives the provider object and fires after the input shown on the authentication input form (if form contains no input, action fires immediately aftertwo_factor_after_authentication_prompt).two_factor_login_backup_linksфильтрует резервные ссылки, отображаемые в форме двухфакторного входа.two_factor_login_nonce_failedaction which fires when a login nonce fails verification. Provides the ID of the user the nonce was presented for as the first argument, and the reason as the second:no_nonce_stored,expired, ormismatch.two_factor_log_login_nonce_failuresfilter overrides whether a failed login nonce verification is written to the PHP error log. Defaults to true forexpiredandmismatch, and false forno_nonce_stored, which any unauthenticated request can reach. Provides the user ID as the second argument and the reason as the third.
WP-CLI Commands
The plugin includes a wp two-factor WP-CLI namespace for managing two-factor authentication from the command line. All commands accept a user by ID, login, or email.
wp two-factor status <user>— Shows a user’s current 2FA status (read-only). Supports--format=json.wp two-factor list-providers— Lists all registered two-factor providers.wp two-factor enable <user> <provider>— Enables a provider for a user. Providers that require a shared secret (like TOTP) can’t be enabled this way and will point you to the profile page instead.wp two-factor disable <user> [<provider>]— Disables a single provider, or performs a full reset of all 2FA for the user when no provider is given. Both forms prompt for confirmation unless--yesis passed.wp two-factor backup-codes generate <user> [--count=<n>]— Generates a fresh set of backup codes for a user, replacing any existing ones. Defaults to 10 codes.wp two-factor unlock <user>— Clears a user’s login rate-limit/throttle without changing their 2FA configuration.
Run wp help two-factor for the full list, or wp help two-factor <command> for options and examples for a specific command.
Перенаправление после проверки двухфакторной аутентификации
Чтобы перенаправить пользователей на определённый URL-адрес после прохождения двухфакторной аутентификации, воспользуйтесь встроенным в ядро WordPress фильтром login_redirect. Этот фильтр работает так же, как и в стандартном процессе входа в WordPress:
add_filter( 'login_redirect', function( $redirect_to, $requested_redirect_to, $user ) {
return home_url( '/dashboard/' );
}, 10, 3 );
Скриншоты




Часто задаваемые вопросы
Какие версии PHP и WordPress поддерживает плагин Two-Factor?
This plugin supports the last two major versions of WordPress and the minimum PHP version supported by those WordPress versions.
Как я могу отправить отзыв или получить помощь с ошибками?
The best place to report bugs, feature suggestions, or any other (non-security) feedback is at the Two Factor GitHub issues page. Before submitting a new issue, please search the existing issues to check if someone else has reported the same feedback.
Куда я могу сообщить об ошибках безопасности?
The plugin contributors and WordPress community take security bugs seriously. We appreciate your efforts to responsibly disclose your findings, and will make every effort to acknowledge your contributions.
Чтобы сообщить о проблеме безопасности, пожалуйста, посетите программу WordPress HackerOne.
Что делать, если я потеряю доступ ко всем своим способам аутентификации?
If you have backup codes enabled, you can use one of those to regain access. If you don’t have backup codes or have used them all, you’ll need to contact your site administrator to reset your account. This is why it’s important to always enable backup codes and keep them in a secure location.
Могу ли я использовать этот плагин с WebAuthn?
The plugin previously supported FIDO U2F, which was a predecessor to WebAuthn. There is an open issue to add WebAuthn support here.
Какой рекомендуемый способ использования ключей-паролей или аппаратных ключей безопасности в рамках двухфакторной аутентификации?
Yes. For passkeys and hardware security keys, you can install the Two-Factor Provider: WebAuthn plugin. It integrates directly with Two-Factor and adds WebAuthn-based authentication as an additional two-factor option for users.
Does this plugin work on WordPress Multisite?
Yes. The Two-Factor plugin is compatible with WordPress Multisite. Each user configures their own 2FA settings via their profile, and because authentication codes are stored in WordPress user meta, the configuration is tied to the user account and valid across all sites in the network. However, there are no network-wide settings — a super admin cannot enforce or configure 2FA globally from the Network Admin dashboard. To manage 2FA for a specific user, edit their profile on any site where they have an account.
How do I disable 2FA for a user who is locked out?
As an administrator, go to Users All Users in the WordPress admin, click Edit on the affected user’s profile, scroll down to the Two-Factor Options section, and uncheck all enabled methods, then click Update User. This will remove 2FA for that user, allowing them to log in with their password alone. You can also do this via WP-CLI with wp two-factor disable —yes, which performs a full reset (see the WP-CLI Commands section above). Once they’re back in, encourage them to re-enable 2FA and generate fresh backup codes.
Can I require 2FA for all users or specific roles?
Not through the plugin’s interface — there are no built-in enforcement settings. However, developers can use the
two_factor_providers_for_userfilter to control which providers are available per user or role, and combine it with custom logic to redirect users who haven’t set up 2FA. Native enforcement support is a known and tracked feature request — follow the discussion at GitHub issue #255.
Отзывы
Участники и разработчики
«Two Factor» — проект с открытым исходным кодом. В развитие плагина внесли свой вклад следующие участники:
Участники«Two Factor» переведён на 43 языка. Благодарим переводчиков за их работу.
Перевести «Two Factor» на ваш язык.
Заинтересованы в разработке?
Посмотрите код, проверьте SVN репозиторий, или подпишитесь на журнал разработки по RSS.
Журнал изменений
0.17.0 — 2026-09-25
- Security Fixes: Ensure that regular passwords can’t bypass the two-factor requirement for REST API and XML-RPC requests by @faisalahammad in #989. Thanks mqrble for responsibly reporting the issue.
- Security Fixes: Add diagnostics for failed login nonce verification by @georgestephanis in #973. Thanks Ananda Dhakal (Patchstack) for responsibly reporting the issue.
- New Features: Add WP-CLI support with
wp two-factorcommands by @masteradhoc in #905 - New Features: Respect intentional bypass via the
two_factor_is_required_for_userfilter by @masteradhoc in #882 - New Features: Add a
two_factor_fallback_provider_for_userfilter for when a user’s stored providers are no longer registered by @masteradhoc in #882 - New Features: Add early notice for soon exhausting recovery codes by @masteradhoc in #907
- New Features: Add privacy policy content registration by @masteradhoc in #869
- Bug Fixes: Fail closed when CSPRNG is unavailable during nonce generation by @dknauss in #877
- Bug Fixes: Only clear the login nonce once it has expired by @georgestephanis in #980
- Bug Fixes: Fix unslashed
REMOTE_ADDRwarning in email provider by @masteradhoc in #975 - Bug Fixes: Fix TOTP verify button after resetting authenticator app by @lakrisgubben in #979
- Bug Fixes: Remove
two_factor_enabled_providersoption on uninstall by @faisalahammad in #903 - Bug Fixes: Fix misleading notice by @masteradhoc in #858
- Bug Fixes: Reword mixed-audience login failure notice to be informational by @dknauss in #922
- Bug Fixes: Rework fail-safe by @masteradhoc in #927
- Bug Fixes: Add coverage for provider-specific fallback notices by @dknauss in #923
- Bug Fixes: Fix HTML5 validation issues by @masteradhoc in #910
- Bug Fixes: Fix users list table fatals (
wp_die) when a user’s 2FA provider is deregistered by @masteradhoc in #933 - Development Updates: Prepare for the WordPress 7.0 release by @masteradhoc in #834
- Development Updates: Prepare for the WordPress 7.1 release by @masteradhoc in #900
- Development Updates: Sync
login_header()andlogin_footer()with WP 7.1 by @masteradhoc in #963 - Development Updates: Update PHPStan to 2.x and exclude
includes/from analysis by @masteradhoc in #972 - Development Updates: Validate against PHPStan version 3, 4 and 5 by @masteradhoc in #948
- Development Updates: Update
wp-coding-standards/wpcsto 3.4.1 by @obenland in #947 - Development Updates: Fix PHPCS and PHPStan issues across multiple files by @aslamdoctor in #818
- Development Updates: Remove
ReflectionProperty::setAccessible()andReflectionMethod::setAccessible()calls in the test suite by @masteradhoc in #942 - Development Updates: Fix Codecov badge by adding OIDC permission for tokenless upload by @nimesh-xecurify in #856
- Development Updates: Update GitHub Actions workflows by @johnbillion in #892
- Development Updates: Update Playground PR preview action to v4 by @obenland in #985
- Development Updates: Add FAQ entries for Multisite, locked-out users, and role enforcement by @masteradhoc in #881
- Development Updates: Update
.mdfiles with the latest two-factor changes and requirements by @masteradhoc in #929 - Development Updates: Update PR template by @masteradhoc in #870
- Development Updates: Unbreak CI: PHPStan false positive and matrix fail-fast by @georgestephanis in #974
- Dependency Updates: Bump the
qrcode-generatorruntime dependency by @kasparsd - Dependency Updates: Bump
qsandexpressby @dependabot[bot] in #895 - Dependency Updates: Bump adm-zip and
@wordpress/scriptsby @dependabot[bot] in #988
0.16.0 — 27.03.2026
- Breaking Changes: Remove legacy FIDO U2F provider support by #439.
- New Features: Add a dedicated settings page for plugin configuration in wp-admin by #764.
- New Features: Add a support links filter so consumers can customize contextual recovery/help links by #615.
- New Features: Refresh backup codes UI styling and behavior by #804.
- Bug Fixes: Delete stored TOTP secrets when the TOTP provider is disabled by #802.
- Bug Fixes: Harden provider handling so login/settings checks do not fail open when expected providers disappear by #586.
- Bug Fixes: Ensure only configured providers are saved and enabled in user settings by #798.
- Bug Fixes: Improve settings-page accessibility and fix profile settings link behavior by #828 and #830.
- Bug Fixes: Resolve PHPCS violations in provider files by #851.
- Development Updates: Move login styles and provider scripts from inline output to enqueued/external assets by #807 and #814.
- Development Updates: Improve inline docs and static-analysis compatibility (WPCS/phpstan) by #810, #815, and #817.
- Development Updates: Improve unit test reliability and integrate CI code coverage reporting by #825, #841, and #842.
- Development Updates: Update readme docs and modernize CI workflow infrastructure by #835, #837, #843, and #849.
- Dependency Updates: Bump
qsfrom 6.14.1 to 6.14.2 by #794. - Dependency Updates: Bump
basic-ftpfrom 5.0.5 to 5.2.0 by #816. - Dependency Updates: Apply automatic lint/format updates and associated Composer package refreshes by #799.
0.15.0 — 13.02.2026
- Breaking Changes: Trigger two-factor flow only when expected by @kasparsd in #660 and #793.
- New Features: Include user IP address and contextual warning in two-factor code emails by @todeveni in #728
- New Features: Optimize email text for TOTP by @masteradhoc in #789
- New Features: Add «Settings» action link to plugin list for quick access to profile by @hardikRathi in #740
- New Features: Additional form hooks by @eric-michel in #742
- New Features: Full RFC6238 Compatibility by @ericmann in #656
- New Features: Consistent user experience for TOTP setup by @kasparsd in #792
- Documentation:
@sincedocs by @masteradhoc in #781 - Documentation: Update user and admin docs, prepare for more screenshots by @jeffpaul in #701
- Documentation: Add changelog & credits, update release notes by @jeffpaul in #696
- Документация: Очистка readme.txt от @masteradhoc в #785
- Documentation: Add date and time information above TOTP setup instructions by @masteradhoc in #772
- Documentation: Clarify TOTP setup instructions by @masteradhoc in #763
- Документация: Обновление RELEASING.md от @jeffpaul в #787
- Development Updates: Pause deploys to SVN trunk for merges to
masterby @kasparsd in #738 - Development Updates: Fix CI checks for PHP compatability by @kasparsd in #739
- Development Updates: Fix Playground refs by @kasparsd in #744
- Development Updates: Persist existing translations when introducing new helper text in emails by @kasparsd in #745
- Development Updates: Fix
missing_direct_file_access_protectionby @masteradhoc in #760 - Development Updates: Fix
mismatched_plugin_nameby @masteradhoc in #754 - Development Updates: Introduce Props Bot workflow by @jeffpaul in #749
- Development Updates: Plugin Check: Fix Missing $domain parameter by @masteradhoc in #753
- Development Updates: Tests: Update to supported WP version 6.8 by @masteradhoc in #770
- Development Updates: Fix PHP 8.5 deprecated message by @masteradhoc in #762
- Development Updates: Exclude 7.2 and 7.3 checks against trunk by @masteradhoc in #769
- Development Updates: Fix Plugin Check errors:
MissingTranslatorsComment&MissingSingularPlaceholderby @masteradhoc in #758 - Development Updates: Add PHP 8.5 tests for latest and trunk version of WP by @masteradhoc in #771
- Development Updates: Add
phpcs:ignorefor falsepositives by @masteradhoc in #777 - Development Updates: Fix(totp):
otpauthlink in QR code URL by @sjinks in #784 - Development Updates: Update deploy.yml by @masteradhoc in #773
- Development Updates: Update required WordPress Version by @masteradhoc in #765
- Development Updates: Fix: ensure execution stops after redirects by @sjinks in #786
- Development Updates: Fix
WordPress.Security.EscapeOutput.OutputNotEscapederrors by @masteradhoc in #776 - Dependency Updates: Bump qs and express by @dependabot[bot] in #746
- Dependency Updates: Bump lodash from 4.17.21 to 4.17.23 by @dependabot[bot] in #750
- Dependency Updates: Bump lodash-es from 4.17.21 to 4.17.23 by @dependabot[bot] in #748
- Dependency Updates: Bump phpunit/phpunit from 8.5.44 to 8.5.52 by @dependabot[bot] in #755
- Dependency Updates: Bump symfony/process from 5.4.47 to 5.4.51 by @dependabot[bot] in #756
- Dependency Updates: Bump qs and body-parser by @dependabot[bot] in #782
- Dependency Updates: Bump webpack from 5.101.3 to 5.105.0 by @dependabot[bot] in #780
0.14.2 — 11.12.2025
- New Features: Add filter for rest_api_can_edit_user_and_update_two_factor_options by @gutobenn in #689
- Development Updates: Remove Coveralls tooling and add inline coverage report by @kasparsd in #717
- Development Updates: Update blueprint path to pull from main branch instead of a deleted f… by @georgestephanis in #719
- Development Updates: Fix blueprint and wporg asset deploys by @kasparsd in #734
- Development Updates: Upload release only on tag releases by @kasparsd in #735
- Development Updates: Bump playwright and @playwright/test by @dependabot[bot] in #721
- Development Updates: Bump tar-fs from 3.1.0 to 3.1.1 by @dependabot[bot] in #720
- Development Updates: Bump node-forge from 1.3.1 to 1.3.2 by @dependabot[bot] in #724
- Development Updates: Bump js-yaml by @dependabot[bot] in #725
- Development Updates: Mark as tested with the latest WP core version by @kasparsd in #730
0.14.1 — 05.09.2025
- Don’t URI encode the TOTP url for display. by @dd32 in #711
- Удален дубликат файла Security.md, автор @slvignesh05 в #712
- Исправлены проблемы с проверкой на ошибки, обнаруженные @sudar в #707
- Update development dependencies and fix failing QR unit test by @kasparsd in #714
- Срабатывание js события change у checkbox, автор @gedeminas, в #688
0.14.0 — 03.07.2025
- Features: Enable Application Passwords for REST API and XML-RPC authentication (by default) by @joostdekeijzer in #697 and #698. Previously this required two_factor_user_api_login_enable filter to be set to true which is now the default during application password auth. XML-RPC login is still disabled for regular user passwords.
- Features: Label recommended methods to simplify the configuration by @kasparsd in #676 and #675
- Documentation: Add WP.org plugin demo by @kasparsd in #667
- Documentation: Document supported versions of WP core and PHP by @jeffpaul in #695
- Documentation: Document the release process by @jeffpaul in #684
- Tooling: Remove duplicate WP.org screenshots and graphics from SVN trunk by @jeffpaul in #683
