### Install scheb/2fa-trusted-device
Source: https://github.com/scheb/2fa/blob/8.x/doc/trusted_device.rst
Install the trusted device package using Composer.
```bash
composer require scheb/2fa-trusted-device
```
--------------------------------
### Install project dependencies
Source: https://github.com/scheb/2fa/blob/8.x/CONTRIBUTING.md
Install all required dependencies for the project in the root directory.
```bash
composer install
```
--------------------------------
### Install scheb/2fa-email Package
Source: https://github.com/scheb/2fa/blob/8.x/doc/providers/email.rst
Install the email authentication provider using Composer.
```bash
composer require scheb/2fa-email
```
--------------------------------
### Install scheb/2fa-google-authenticator
Source: https://github.com/scheb/2fa/blob/8.x/doc/providers/google.rst
Install the Google Authenticator provider using Composer.
```bash
composer require scheb/2fa-google-authenticator
```
--------------------------------
### Install scheb/2fa-totp
Source: https://github.com/scheb/2fa/blob/8.x/doc/providers/totp.rst
Install the TOTP two-factor provider using Composer.
```bash
composer require scheb/2fa-totp
```
--------------------------------
### Install SchebTwoFactorBundle (Alternative)
Source: https://github.com/scheb/2fa/blob/8.x/doc/installation.rst
Use this alternative Composer command to install the bundle.
```bash
composer require scheb/2fa-bundle
```
--------------------------------
### Install scheb/2fa-backup-code
Source: https://github.com/scheb/2fa/blob/8.x/doc/backup_codes.rst
Install the backup code package using Composer. This is a prerequisite for using the feature.
```terminal
composer require scheb/2fa-backup-code
```
--------------------------------
### Install SchebTwoFactorBundle with Composer
Source: https://github.com/scheb/2fa/blob/8.x/doc/installation.rst
Use this command to install the core bundle if you are using Symfony Flex.
```bash
composer require 2fa
```
--------------------------------
### Install Optional SchebTwoFactorBundle Features
Source: https://github.com/scheb/2fa/blob/8.x/doc/installation.rst
Install additional packages to extend the bundle's functionality based on your needs.
```bash
composer require scheb/2fa-backup-code # Add backup code feature
```
```bash
composer require scheb/2fa-trusted-device # Add trusted devices feature
```
```bash
composer require scheb/2fa-totp # Add two-factor authentication using TOTP
```
```bash
composer require scheb/2fa-google-authenticator # Add two-factor authentication with Google Authenticator
```
```bash
composer require scheb/2fa-email # Add two-factor authentication using email
```
--------------------------------
### Install Symfony Mailer
Source: https://github.com/scheb/2fa/blob/8.x/doc/providers/email.rst
Install the Symfony Mailer component if you are using it to send emails.
```bash
composer require symfony/mailer
```
--------------------------------
### Install Scheb Two-Factor Bundle Packages
Source: https://github.com/scheb/2fa/blob/8.x/UPGRADE.md
Add extra packages to your application depending on the bundle features you are using. These commands install specific features like backup codes, trusted devices, TOTP, Google Authenticator, or email authentication.
```bash
composer require scheb/2fa-backup-code # Add backup code feature
```
```bash
composer require scheb/2fa-trusted-device # Add trusted devices feature
```
```bash
composer require scheb/2fa-totp # Add two-factor authentication using TOTP
```
```bash
composer require scheb/2fa-google-authenticator # Add two-factor authentication with Google Authenticator
```
```bash
composer require scheb/2fa-email # Add two-factor authentication using email
```
--------------------------------
### TwoFactorProviderInterface: prepareAuthentication Method
Source: https://github.com/scheb/2fa/blob/8.x/doc/providers/custom.rst
This method is for any necessary preparation work for the two-factor provider. For example, the email provider generates and sends a code to the user here.
```php
public function prepareAuthentication(object $user): void;
```
--------------------------------
### User Entity Implementation (PHP Annotations)
Source: https://github.com/scheb/2fa/blob/8.x/doc/providers/google.rst
Implement the TwoFactorInterface for your user entity to support Google Authenticator. This example uses PHP annotations for mapping.
```php-annotations
googleAuthenticatorSecret;
}
public function getGoogleAuthenticatorUsername(): ?string
{
return $this->username;
}
public function getGoogleAuthenticatorSecret(): ?string
{
return $this->googleAuthenticatorSecret;
}
public function setGoogleAuthenticatorSecret(?string $googleAuthenticatorSecret): void
{
$this->googleAuthenticatorSecret = $googleAuthenticatorSecret;
}
}
```
--------------------------------
### Example JSON Payload for Sending 2FA Code
Source: https://github.com/scheb/2fa/blob/8.x/doc/api.rst
This is an example of a JSON payload that can be used to send the two-factor authentication code to the '2fa check' path.
```json
{"data": {"authCode": "1234"}}
```
--------------------------------
### User Entity Implementation (PHP Attributes)
Source: https://github.com/scheb/2fa/blob/8.x/doc/providers/google.rst
Implement the TwoFactorInterface for your user entity to support Google Authenticator. This example uses PHP attributes for mapping.
```php-attributes
googleAuthenticatorSecret;
}
public function getGoogleAuthenticatorUsername(): ?string
{
return $this->username;
}
public function getGoogleAuthenticatorSecret(): ?string
{
return $this->googleAuthenticatorSecret;
}
public function setGoogleAuthenticatorSecret(?string $googleAuthenticatorSecret): void
{
$this->googleAuthenticatorSecret = $googleAuthenticatorSecret;
}
}
```
--------------------------------
### User Entity with TOTP (Attributes)
Source: https://github.com/scheb/2fa/blob/8.x/doc/providers/totp.rst
Implement the TwoFactorInterface for your user entity using PHP attributes to enable TOTP authentication. This example demonstrates defining the TOTP secret and retrieving configuration.
```php-attributes
totpSecret ? true : false;
}
public function getTotpAuthenticationUsername(): string
{
return $this->username;
}
public function getTotpAuthenticationConfiguration(): ?TotpConfigurationInterface
{
// You could persist the other configuration options in the user entity to make it individual per user.
return new TotpConfiguration($this->totpSecret, TotpConfiguration::ALGORITHM_SHA1, 20, 8);
}
}
```
--------------------------------
### User Entity with TOTP (Annotations)
Source: https://github.com/scheb/2fa/blob/8.x/doc/providers/totp.rst
Implement the TwoFactorInterface for your user entity using Doctrine annotations to enable TOTP authentication. This example shows how to define the TOTP secret and retrieve configuration.
```php-annotations
totpSecret ? true : false;
}
public function getTotpAuthenticationUsername(): string
{
return $this->username;
}
public function getTotpAuthenticationConfiguration(): ?TotpConfigurationInterface
{
// You could persist the other configuration options in the user entity to make it individual per user.
$period = 20;
$digits = 6;
return null !== $this->totpSecret ? new TotpConfiguration($this->totpSecret, TotpConfiguration::ALGORITHM_SHA1, $period, $digits) : null;
}
}
```
--------------------------------
### Run unit and integration tests
Source: https://github.com/scheb/2fa/blob/8.x/CONTRIBUTING.md
Commands to execute the test suite in the root or application directory.
```bash
vendor/bin/phpunit
```
--------------------------------
### Configure Firewall for Two-Factor Authentication
Source: https://github.com/scheb/2fa/blob/8.x/doc/installation.rst
Set up the firewall in security.yaml to handle two-factor authentication routes for login and checking.
```yaml
security:
firewalls:
your_firewall_name:
two_factor:
auth_form_path: 2fa_login # The route name you have used in the routes.yaml
check_path: 2fa_login_check # The route name you have used in the routes.yaml
# The path patterns shown here have to be updated according to your routes.
# IMPORTANT: ADD THESE ACCESS CONTROL RULES AT THE VERY TOP OF THE LIST!
access_control:
# This makes the logout route accessible during two-factor authentication. Allows the user to
# cancel two-factor authentication, if they need to.
- { path: ^/logout, role: PUBLIC_ACCESS }
# This ensures that the form can only be accessed when two-factor authentication is in progress.
- { path: ^/2fa, role: IS_AUTHENTICATED_2FA_IN_PROGRESS }
# Other rules may follow here...
```
--------------------------------
### Configure Leeway for Google and TOTP
Source: https://github.com/scheb/2fa/blob/8.x/UPGRADE.md
Replace window configuration with leeway for time drift management in YAML configuration.
```yaml
# config/packages/scheb_2fa.yaml
scheb_two_factor:
google:
leeway: 10 # Acceptable time drift in seconds, must be less or equal than 30 seconds
# TOTP authentication config
totp:
leeway: 10 # Acceptable time drift in seconds, must be less or equal than the TOTP period
```
--------------------------------
### Get TOTP QR Code Content
Source: https://github.com/scheb/2fa/blob/8.x/doc/providers/totp.rst
Retrieve the content required to generate a QR code for TOTP authentication using the 'scheb_two_factor.security.totp_authenticator' service.
```php
$qrCodeContent = $container->get("scheb_two_factor.security.totp_authenticator")->getQRContent($user);
```
--------------------------------
### Migrate bundle configuration and packages
Source: https://github.com/scheb/2fa/blob/8.x/UPGRADE.md
Commands to rename configuration files and switch composer dependencies during the upgrade to version 5.
```bash
# Rename configuration files. This is actually not required, but good to do for consistency. Also, Symfony
# Flex doesn't remove the config files when the "composer remove" command is later executed.
mv config/packages/scheb_two_factor.yaml config/packages/scheb_2fa.yaml
mv config/routes/scheb_two_factor.yaml config/routes/scheb_2fa.yaml # Might not exist, then ignore.
# Switch composer packages
composer remove scheb/two-factor-bundle --no-scripts
composer require scheb/2fa-bundle
```
--------------------------------
### Configure Custom Services
Source: https://github.com/scheb/2fa/blob/8.x/doc/providers/email.rst
Register custom services in the bundle configuration file.
```yaml
# config/packages/scheb_2fa.yaml
scheb_two_factor:
email:
mailer: acme.custom_mailer_service
```
```yaml
# config/packages/scheb_2fa.yaml
scheb_two_factor:
email:
code_generator: acme.custom_code_generator_service
```
```yaml
# config/packages/scheb_2fa.yaml
scheb_two_factor:
email:
template: security/2fa_form.html.twig
```
```yaml
# config/packages/scheb_2fa.yaml
scheb_two_factor:
email:
form_renderer: acme.custom_form_renderer_service
```
--------------------------------
### Configure Firewall for Two-Factor Authentication
Source: https://github.com/scheb/2fa/blob/8.x/doc/api.rst
Ensure your firewall is stateful and enable two-factor authentication preparation on login and access denial.
```yaml
security:
firewalls:
your_firewall_name:
# ...
two_factor:
prepare_on_login: true
prepare_on_access_denied: true
```
--------------------------------
### Full Email Authentication Configuration Reference
Source: https://github.com/scheb/2fa/blob/8.x/doc/providers/email.rst
Reference for all available configuration options for the email authentication provider.
```yaml
# config/packages/scheb_2fa.yaml
scheb_two_factor:
email:
enabled: true # If email authentication should be enabled, default false
mailer: acme.custom_mailer_service # Use alternative service to send the authentication code
code_generator: acme.custom_code_generator_service # Use alternative service to generate authentication code
sender_email: me@example.com # Sender email address
sender_name: John Doe # Sender name
digits: 4 # Number of digits in authentication code
template: security/2fa_form.html.twig # Template used to render the authentication form
```
--------------------------------
### Enable SchebTwoFactorBundle in config/bundles.php
Source: https://github.com/scheb/2fa/blob/8.x/doc/installation.rst
Enable the bundle by adding its class to your config/bundles.php file. This step is automatic if using Symfony Flex.
```php
return [
// ...
Scheb\TwoFactorBundle\SchebTwoFactorBundle::class => ['all' => true],
];
```
--------------------------------
### Retrieve QR Code Content for Google Authenticator
Source: https://github.com/scheb/2fa/blob/8.x/doc/providers/google.rst
Get the QR code content from the Google Authenticator service to generate a scannable QR code for the app. Ensure the QR code content is kept within your application and not exposed to external services.
```php
$qrCodeContent = $container->get("scheb_two_factor.security.google_authenticator")->getQRContent($user);
```
--------------------------------
### Implement TrustedDeviceInterface with PHP Annotations
Source: https://github.com/scheb/2fa/blob/8.x/doc/trusted_device.rst
Implement the TrustedDeviceInterface in your User entity using Doctrine annotations to manage trusted device versions.
```php
trustedVersion;
}
}
```
--------------------------------
### Implement TrustedDeviceInterface with PHP Attributes
Source: https://github.com/scheb/2fa/blob/8.x/doc/trusted_device.rst
Implement the TrustedDeviceInterface in your User entity using PHP attributes for managing trusted device versions.
```php
trustedVersion;
}
}
```
--------------------------------
### Configure Two-Factor Bundle Renderer
Source: https://github.com/scheb/2fa/blob/8.x/doc/firewall_template.rst
Update the bundle configuration to use the custom service for rendering the authentication form.
```yaml
# config/packages/scheb_2fa.yaml
scheb_two_factor:
google: # Or "totp" or "email", depending on the two-factor provider you're using
enabled: true
form_renderer: acme.custom_form_renderer
```
--------------------------------
### Implement Two-Factor Authentication Success Handler
Source: https://github.com/scheb/2fa/blob/8.x/doc/api.rst
Implement this handler to return a response indicating that two-factor authentication has been completed successfully. Configure it as the 'success_handler' in your firewall settings.
```php
template path]
) {
}
public function renderForm(Request $request, array $templateVars): Response
{
$firewallName = $this->firewallMap->getFirewallConfig($request)->getName();
$template = $this->templates[$firewallName];
$content = $this->twigEnvironment->render($template, $templateVars);
$response = new Response();
$response->setContent($content);
return $response;
}
}
```
--------------------------------
### Configure Custom IP Whitelist Provider
Source: https://github.com/scheb/2fa/blob/8.x/doc/configuration.rst
Specify a custom service to implement the IpWhitelistProviderInterface for dynamic IP whitelisting logic.
```yaml
ip_whitelist_provider: acme.custom_ip_whitelist_provider
```
--------------------------------
### Enable Trusted Device Feature in Configuration
Source: https://github.com/scheb/2fa/blob/8.x/doc/trusted_device.rst
Configure the scheb_two_factor bundle to enable the trusted device feature and set its parameters.
```yaml
scheb_two_factor:
trusted_device:
enabled: false # If the trusted device feature should be enabled
lifetime: 5184000 # Lifetime of the trusted device token
extend_lifetime: false # Automatically extend lifetime of the trusted cookie on re-login
cookie_name: trusted_device # Name of the trusted device cookie
cookie_secure: false # Set the 'Secure' (HTTPS Only) flag on the trusted device cookie
cookie_same_site: "lax" # The same-site option of the cookie, can be "lax" or "strict"
cookie_domain: ".example.com" # Domain to use when setting the cookie, fallback to the request domain if not set
cookie_path: "/" # Path to use when setting the cookie
```
--------------------------------
### Enable TOTP Authentication
Source: https://github.com/scheb/2fa/blob/8.x/doc/providers/totp.rst
Enable TOTP authentication in your application's configuration.
```yaml
scheb_two_factor:
totp:
enabled: true
```
--------------------------------
### Use Custom Backup Code Manager
Source: https://github.com/scheb/2fa/blob/8.x/doc/backup_codes.rst
Configure the system to use a custom backup code manager by specifying its service ID in the scheb_2fa.yaml configuration.
```yaml
# config/packages/scheb_2fa.yaml
scheb_two_factor:
backup_codes:
manager: acme.custom_backup_code_manager # Use a custom backup code manager
```
--------------------------------
### Enable Google Authenticator in Configuration
Source: https://github.com/scheb/2fa/blob/8.x/doc/providers/google.rst
Enable the Google Authenticator authentication method in your application's configuration file.
```yaml
# config/packages/scheb_2fa.yaml
scheb_two_factor:
google:
enabled: true
```
--------------------------------
### Enable Email Authentication
Source: https://github.com/scheb/2fa/blob/8.x/doc/providers/email.rst
Enable email-based two-factor authentication and configure the sender's email and name.
```yaml
# config/packages/scheb_2fa.yaml
scheb_two_factor:
email:
enabled: true
sender_email: no-reply@example.com
sender_name: John Doe # Optional
```
--------------------------------
### TwoFactorProviderInterface: needsPreparation Method
Source: https://github.com/scheb/2fa/blob/8.x/doc/providers/custom.rst
Determines if the provider requires preparation. If false, the prepareAuthentication method will not be called, useful for stateless providers like TOTP.
```php
public function needsPreparation(): bool;
```
--------------------------------
### Implement Custom Trusted Device Manager Logic
Source: https://github.com/scheb/2fa/blob/8.x/doc/trusted_device.rst
Implement the `canSetTrustedDevice` method in a custom trusted device manager to define conditions for flagging a device as trusted.
```php
public function canSetTrustedDevice($user, Request $request, string $firewallName): bool
{
```
--------------------------------
### Google Authenticator Configuration Reference
Source: https://github.com/scheb/2fa/blob/8.x/doc/providers/google.rst
Configure advanced settings for Google Authenticator, including server name, issuer, digits, and leeway.
```yaml
# config/packages/scheb_2fa.yaml
scheb_two_factor:
google:
enabled: true # If Google Authenticator should be enabled, default false
server_name: Server Name # Server name used in QR code
issuer: Issuer Name # Issuer name used in QR code
digits: 6 # Number of digits in authentication code
leeway: 0 # Acceptable time drift in seconds, must be less or equal than 30 seconds
```
--------------------------------
### Configure Firewall to Allow POST Only False
Source: https://github.com/scheb/2fa/blob/8.x/UPGRADE.md
Change the `check_path` to accept two-factor authentication codes with requests other than POST. Set `post_only: false` on the firewall configuration.
```yaml
security:
firewalls:
yourFirewallName:
# ...
two_factor:
post_only: false
```
--------------------------------
### TwoFactorProviderInterface: beginAuthentication Method
Source: https://github.com/scheb/2fa/blob/8.x/doc/providers/custom.rst
This method is called after a successful login. It should return true if the user needs to be prompted for two-factor authentication, and false otherwise. It receives an AuthenticationContextInterface object.
```php
public function beginAuthentication(AuthenticationContextInterface $context): bool;
```
--------------------------------
### Implement Two-Factor Authentication Required Handler
Source: https://github.com/scheb/2fa/blob/8.x/doc/api.rst
Implement this handler to return a response indicating that two-factor authentication is required. Configure it as the 'required_handler' in your firewall settings.
```php
backupCodes);
}
/**
* Invalidate a backup code
*/
public function invalidateBackupCode(string $code): void
{
$key = array_search($code, $this->backupCodes);
if ($key !== false){
unset($this->backupCodes[$key]);
}
}
/**
* Add a backup code
*/
public function addBackUpCode(string $backUpCode): void
{
if (!in_array($backUpCode, $this->backupCodes)) {
$this->backupCodes[] = $backUpCode;
}
}
}
```
--------------------------------
### Implement Custom 2FA Form Renderer
Source: https://github.com/scheb/2fa/blob/8.x/doc/providers/google.rst
Implement the TwoFactorFormRendererInterface to fully customize the 2FA form rendering logic. Register the class as a service and update configuration.
```php
email;
}
public function getEmailAuthCode(): string
{
if (null === $this->authCode) {
throw new \LogicException('The email authentication code was not set');
}
return $this->authCode;
}
public function setEmailAuthCode(string $authCode): void
{
$this->authCode = $authCode;
}
}
```
--------------------------------
### Configure Authentication Mechanism Success Handler
Source: https://github.com/scheb/2fa/blob/8.x/doc/api.rst
Set your custom success handler for the specific authentication mechanism, such as json_login, in your security configuration.
```yaml
security:
firewalls:
your_firewall_name:
json_login: # The authentication mechanism you're using
success_handler: your_api_success_handler
```
--------------------------------
### Enable CSRF Protection in Framework Configuration
Source: https://github.com/scheb/2fa/blob/8.x/doc/csrf_protection.rst
Ensure CSRF protection is enabled in the main framework configuration file.
```yaml
# config/packages/framework.yaml
framework:
csrf_protection: ~
```
--------------------------------
### User Entity with Backup Codes (PHP Attributes)
Source: https://github.com/scheb/2fa/blob/8.x/doc/backup_codes.rst
Implement the BackupCodeInterface in your User entity using PHP attributes. This includes methods for checking, invalidating, and adding backup codes.
```php-attributes
backupCodes);
}
/**
* Invalidate a backup code
*/
public function invalidateBackupCode(string $code): void
{
$key = array_search($code, $this->backupCodes);
if ($key !== false){
unset($this->backupCodes[$key]);
}
}
/**
* Add a backup code
*/
public function addBackUpCode(string $backUpCode): void
{
if (!in_array($backUpCode, $this->backupCodes)) {
$this->backupCodes[] = $backUpCode;
}
}
}
```
--------------------------------
### Custom API Login Success Handler for 2FA
Source: https://github.com/scheb/2fa/blob/8.x/doc/api.rst
Implement a custom success handler to return a specific JSON response when two-factor authentication is required after initial login.
```php
getEmailAuthCode();
// Send email
}
}
```
--------------------------------
### Register Custom Form Renderer Service
Source: https://github.com/scheb/2fa/blob/8.x/doc/providers/totp.rst
Register a custom form renderer as a service and update the bundle configuration to use it for rendering the two-factor authentication form.
```yaml
# config/packages/scheb_2fa.yaml
scheb_two_factor:
totp:
form_renderer: acme.custom_form_renderer_service
```
--------------------------------
### Register Custom Provider (XML Configuration)
Source: https://github.com/scheb/2fa/blob/8.x/doc/providers/custom.rst
Register your custom two-factor provider service in XML. Use the 'tag' element with 'name' and 'alias' attributes for 'scheb_two_factor.provider'.
```xml
```
--------------------------------
### Configure Two-Factor Authentication Code Parameter Name
Source: https://github.com/scheb/2fa/blob/8.x/doc/api.rst
Customize the POST parameter name used for sending the two-factor authentication code in your firewall configuration.
```yaml
security:
firewalls:
your_firewall_name:
# ...
two_factor:
auth_code_parameter_name: _auth_code # Name of the parameter for the two-factor authentication code
```
--------------------------------
### Registering a Custom Provider
Source: https://github.com/scheb/2fa/blob/8.x/doc/providers/custom.rst
How to register your custom provider service in the Symfony container using the required tag.
```APIDOC
## Registering the Provider
### Description
Register your provider class as a service and tag it with `scheb_two_factor.provider` to make it available to the bundle.
### Configuration
- **Tag Name**: `scheb_two_factor.provider`
- **Alias**: Must be a unique identifier (e.g., `acme_two_factor_provider`)
### YAML Example
```yaml
services:
acme.custom_two_factor_provider:
class: Acme\Demo\MyTwoFactorProvider
tags:
- { name: scheb_two_factor.provider, alias: acme_two_factor_provider }
```
### XML Example
```xml
```
```
--------------------------------
### Implement Custom 2FA Condition
Source: https://github.com/scheb/2fa/blob/8.x/doc/custom_conditions.rst
Create a class implementing TwoFactorConditionInterface to define custom logic for triggering 2FA.
```php
email;
}
public function getEmailAuthCode(): string
{
if (null === $this->authCode) {
throw new \LogicException('The email authentication code was not set');
}
return $this->authCode;
}
public function setEmailAuthCode(string $authCode): void
{
$this->authCode = $authCode;
}
}
```
--------------------------------
### Configure Custom Two-Factor Provider Decider
Source: https://github.com/scheb/2fa/blob/8.x/doc/configuration.rst
Specify a custom service implementing TwoFactorProviderDeciderInterface to determine which two-factor provider to prioritize.
```yaml
two_factor_provider_decider: acme.custom_two_factor_provider_decider
```
--------------------------------
### Configure IP Whitelist in YAML
Source: https://github.com/scheb/2fa/blob/8.x/doc/configuration.rst
Define a list of IP addresses and subnets that are allowed to bypass two-factor authentication. Supports IPv4, IPv6, and private subnets.
```yaml
ip_whitelist:
- 127.0.0.1 # One IPv4
- 192.168.0.0/16 # One IPv4 subnet
- 2001:0db8:85a3:0000:0000:8a2e:0370:7334 # One IPv6
- 2001:db8:abcd:0012::0/64 # One IPv6 subnet
- !php/const Symfony\Component\HttpFoundation\IpUtils::PRIVATE_SUBNETS # All private IPv4 and IPv6 subnets
```