Autenticación de dos factores con Node.js -

Existe una variedad de estrategias para proteger sus importantes credenciales en línea. A menudo escuchamos sobre administradores y generadores de contraseñas, pero para mí, la estrategia más importante es utilizar la autenticación de dos factores (2FA). Las contraseñas se pueden adivinar, los números de teléfono se pueden falsificar, pero el uso de la autenticación de dos factores esencialmente requiere que el usuario esté en posesión de un dispositivo físico con una aplicación como Google Authenticator, cargada con una clave secreta para la aplicación. dada, lo que proporciona una capa adicional de seguridad.

No solía tomarme en serio la autenticación de dos factores, hasta que alguien robó mi nombre de dominio e intentó lavarlo en un refugio seguro para dominios robados. Si bien no sé exactamente cómo lo hicieron, estoy bastante seguro de que obtuvo acceso a mi dirección de correo electrónico, crearon filtros para que no pudiera ver los correos electrónicos, etc. Si hubiera usado la autenticación de dos factores, ni mi correo electrónico ni Ve papi. Se podría haber accedido a las cuentas. O podría quitárselo a Cody Brown, a quien lerobaron $8,000 en criptomonedas en minutos porque el proveedor usó la validación del número de teléfono para permitir que se aprobaran las transacciones. Hoy en día utilizo la autenticación de dos factores para todas mis cuentas importantes de correo electrónico, laboral y financiera.

Como uso 2FA con tanta frecuencia, quería ver cómo un desarrollador gestiona el proceso para sus usuarios. Eso incluiría generar la clave secreta, crear su representación de código QR, escanear el código en Google Authenticator (realizado por el usuario) y luego validar ese código proporcionado por GA con la clave del usuario. ¡Encontré una biblioteca Node.js fácil de usar, Speakeasy, para hacerlo!

Índice de contenidos
  1. Paso de configuración 1: generar una clave secreta
  2. Paso de configuración 2: generar una imagen QR
  3. User Step 1: Scanthe QR Code/ Add Site to Authenticator
  4. User Step 2: Providingthe Token / Validating the Token
  5. Live Demo

Paso de configuración 1: generar una clave secreta

Suponiendo que haya instalado Speakeasy a través de npm install speakeasy, la configuración de autenticación de dos factores se inicia generando una clave secreta única para el usuario:

var clandestino = require('speakeasy');var secreto = clandestino.generateSecret({longitud: 20});console.log(secret.base32); // Guarde este valor en su base de datos para el usuario// Ejemplo: JFBVG4R7ORKHEZCFHZFW26L5F55SSP2Y

Esta clave secreta debe almacenarse con el registro del usuario en su base de datos, ya que se utilizará como referencia para validar códigos 2FA en el futuro.

Paso de configuración 2: generar una imagen QR

Aplicaciones como Google Authenticator permiten a los usuarios escanear un código QR o ingresar la clave de texto. Escanear una imagen es mucho más rápido por lo que ofrecer el código QR será de gran comodidad para tu usuario:

var QRCode = require('qrcode');QRCode.toDataURL(secret.otpauth_url, function(err, image_data) { console.log(image_data); // Un URI de datos para la imagen del código QR});

QRCode.toDataURLproporciona unURI de datos de imagen que puede utilizar para el imgsrcatributo. Si no está familiarizado con un código QR, se verá así:

User Step 1: Scanthe QR Code/ Add Site to Authenticator

At thispoint the user should have opened Google Authenticator (or Authy, etc.) and scanned the QR code; an entry foryour web appwillbe added withinthe device’s app. From this point forward, whenever the user wants to log in(or perform any action you’d like to be protected), your system should recognize the user wants to use 2FA and you should require they enter the tokenfrom their app.

For the purposes of debugging, you can get what should be the user code value at a given time via:

// Load the secret.base32 from their user record in databasevar secret = ...var token = speakeasy.totp({  secret: secret,  encoding: 'base32'});

User Step 2: Providingthe Token / Validating the Token

When your web app prompts theuser for the current 2FA token, and the user provides a 6 digit token, the web app must validate thattoken:

// This is provided the by the user via form POSTvar userToken = params.get('token');// Load the secret.base32 from their user record in databasevar secret = ...// Verify that the user token matches what it should at this momentvar verified = speakeasy.totp.verify({  secret: secret,  encoding: 'base32',  token: userToken});

If the token matches, the user can be trusted; if the token does not match, the web app should prompt the user to tryagain. Remember that Authenticator provides a new token every {x} seconds so an incorrect token shouldn’timmediately raise a red flag; the token may have simply expired by the time the user submitted the form.

Live Demo

The speakeasy developers have created alive speakeasy 2FA demo for you to play with so that you can understand the steps involvedfrom both a user and a developer perspective.

This post is only meant to be a brief, high level overview of implementing two-factor authentication — please read thespeakeasy documentation to get a more detailed explanation as well as learn about more specific 2FA options. In an ideal world, two-factor authentication would be enabled by default for most logins, howeverit can be confusing for the majority of web users (think of the very non-technical user), so I can understandwhy 2FA is considered an extra security measure for now. A bigthanks to speakeasy’s developersfor their easy to use Node.js library, awesome documentation, and simple demo!

Te podría interesar...

Deja una respuesta

Subir