Install and configure two-step authentication on a Drupal 8/9 site

Instalar y configurar la autenticación en dos pasos en un sitio Drupal 8/9

Two-factor authentication is a means of identifying a user through two separate pieces of information or identification. For your Drupal site, these two parts are your account password and a one-time password generated using a third-party mobile authenticator. By combining proof of identity – which an unauthorized user is unlikely to possess – two-factor authentication provides a higher level of security for your website users.

The Two-factor Authentication (TFA) module

To configure two-step authentication on a Drupal site, we have the Two-factor Authentication (TFA) module which works as a base module, that is, by itself it does not offer two-step authentication but rather provides a series of interfaces that allow connecting a two-step authentication method with Drupal.

The TFA module can be installed like other Drupal modules by placing the module directory in the Drupal file system (for example, in sites/all/modules)

Two-factor Authentication (TFA) | Drupal.org

O usando composer (recomendado)

composer require drupal/tfa

Very important, make sure you are running Drupal on PHP 7.4 or higher as otherwise it will throw a very strange error that in my case took me several hours to determine the cause.

Once downloaded, enable it on the Drupal modules page.

The Google Authentication login module

As I mentioned earlier, the TFA module only creates interfaces for us that allow other modules to manage the particular two-factor authentication they offer, such as the Google Authenticator login module.

art 1

This module, which works as a complement to the TFA module, allows us to use Google's two-step authentication management tool called Authenticator.

Surely for some users who have Gmail accounts it may seem familiar since it is the same tool they use for two-step authentication for their accounts.

The module can be installed like other Drupal modules by placing the module directory in the Drupal file system (for example, in sites/all/modules)

Google Authenticator login | Drupal.org
O usando composer (recomendado)

composer require drupal/ga_login

Once downloaded, enable it on the Drupal modules page.

The Encrypt and real AES modules

For the configuration we will require an encryption method that allows us to store our key safely in the system, so we need to install the Encrypt module which provides us with an API to perform symmetric and asymmetric encryption.

Real AES on the other hand, is a module that provides an AES encryption method for the Encrypt module using CBC

Both modules can be downloaded from their project pages on drupal.org

Encrypt | Drupal.org

Real AES | Drupal.org

Using composer (recommended)

composer require drupal/encrypt
composer require drupal/real_aes

Encryption key setup

Once we have all the necessary modules downloaded and installed, the first thing we need to do is add a profile, for that we go to Settings -> System -> Encryption Profiles

Or we can also arrive by the following route

/admin/config/system/encryption/profiles/add

Once there, we enter a name for the key, enter a legible and easily identifiable name, for example the name of your site.

In Type Settings select the type as Encryption and in Size 256

art 2

Below we must add the encryption key value, this key must be 256 bits, we can generate it with some tool or you can use an online one like the one I share with you in the following link:

Encryption Key Generator (acte.ltd/utils/randomkeygen)

When generating the key, make sure 256-bit is selected

art 6

The value generated in the text field will be the value to be used in the key value field.

art 5

Setting up Two-Step Authentication

Now we have to configure the two-step authentication that we are going to use.

Go to Users -> Two-Step Verification.

O a la ruta /admin/config/people/tfa

Habilitela

art 4

En los complementos a utilizar, habilite el ingreso con GA login basado en tiempo que es que corresponde a Google Authenticator y el de código de recuperación que nos servirá para generar códigos que podemos guardar en caso que perdamos el acceso al Google Authenticator.

art 8

En las configuraciones Adicionales en el número de códigos aceptados escriba 2, en el Emisor escriba un nombre corto como “Mi sitio” o algo así que le permita identificar al usuario en la aplicación móvil  el sitio al que corresponde el código.

En el perfil de cifrado, seleccione el perfil que creó en el paso anterior.

En saltar validación defina el valor en 3.

art 8

Los siguientes valores los puede dejar por defecto o ajustarlos a como se ven en la imagen

En la parte final podrá ver unos mensajes que se le enviarán al usuario por correo una vez finalice el proceso de configuración, asegúrese de que estén en el idioma de su sitio o ajuste según le convenga.

Finalmente, guarde la configuración.

art 11

De esta forma hemos finalizado la configuración del módulo y cada usuario podrá habilitarla desde su panel administrativo.

Note que no configuramos la opción que hace obligatorio el uso de la autenticación en dos pasos a los usuarios dentro de los roles seleccionados, esto lo hacemos así a fin de no bloquear las cuentas de los usuarios cuando aún no las han configurado, un vez usted esté seguro que todos los usuarios la han configurado es recomendable configurar esta opción.

art 12

Cómo habilitarla (Como usuario)

  1. En su dispositivo móvil descargue la aplicación Google Authenticator

               a. Para Android haga clic en este enlace.

               b. Para iOS haga clic en este enlace.

      2. Ingrese a su cuenta en su sitio Drupal como normalmente lo hace.

      3. En la barra administrativa superior haga clic sobre su nombre de usuario, este desplegará una barra con                    opciones, haga clic en Editar perfil

drupal 1

    4. En las opciones que verá, haga clic en Seguridad

drupal 2

    5. En la primera opción para habilitar la Aplicación para autenticación de dos factores Haga clic en configurar                aplicación.

drupal 3

   6. Ingrese la contraseña de su cuenta, esta se solicita nuevamente por seguridad, posteriormente presione el               botón Confirmar.

drupal 4

   7. Ahora verá una página donde podrá ver entre otras cosas un código QR. Abra la aplicación Google                           Authenticator en su dispositivo móvil, podrá ver una interfaz similar a la imagen que verá a continuación, como         en esa imágen, presione la el ícono +  para agregar y seleccione Escanear un código QR.

screen

   8. Scan the QR code and a 6-digit 2FA code will be randomly generated within your Google Authenticator APP. Enter the generated 6-digit code into your Google Authenticator and click enter and verify, make sure to enter the code before the countdown indicator on the right ends.

QR

   9. Upon completion and if everything has gone well, you will see a confirmation message in a green stripe and additional information below the date on which the option was enabled. You will also receive a message to your email address confirming that you have enabled the option. 

drupal 20

   10. Now note that below is the Recovery Codes option, we are also going to configure this option to generate fixed codes that we can use in the future in case we lose access to the application or if for some reason that method does not work. Click Generate Codes.

drupal 21

  11. You will be asked for the password again, enter it and press Confirm

drupal 22

 12. Note that a list of codes has been generated, copy them and save them in a safe place, so that if you need them you can use them. Finally press the button Save codes to account

codigos de rec

   13.Again you will see the confirmation in the green strip, and you will also see that the option to see the codes that have been generated or to reset them is enabled; with this we are finished.

How to use it (As a user)

Once you have enabled two-step verification, every time you enter the website after logging in as normal, you will now see an additional step where it will ask you for the app verification code.

  1. Open the Google Authenticator app on your mobile device
  2. Locate the record for the site and enter the code in the field, press the Verify button

como usuario

   3. Note that in case you do not have the application or it is failing, you can use the codes generated by clicking on Two-factor verification recovery code.

Known issues:

If at any point in the configuration you see something like the following message, it is because you need php 7.4

Parse error: syntax error, unexpected 'SettingsContainerInterface' 
(T_STRING), expecting function (T_FUNCTION) or const (T_CONST) in C:\laragon\www\testeqrcode_php\vendor\chillerlan\php-qrcode\src\QRCode.
php on line 153

We hope you found this explanation of installing, configuring, and using two-factor authentication for Drupal helpful.