Un generador para contraseñas basadas (RFC 4226) y basadas en el tiempo (RFC 6238) contraseñas únicas (OTP). (¡También conocido como otra implementación de Google Authenticator!)
ext-curl PARA SINCRONIZACIÓN DE TIEMPO DEL SERVER DE SOBREext-sodium para implementaciones de tiempo constante de Base64 codifica/decode y hex2bin/bin2hex ( paragonie/constant_time_encoding se usa como altavalcado) Requiere compositor
Vía terminal: composer require chillerlan/php-authenticator
compositor.json
{
"require" : {
"php" : " ^8.2 " ,
"chillerlan/php-authenticator" : " dev-main "
}
} Nota: Reemplace dev-main con una restricción de versión, por ejemplo, ^5.0 - Consulte las versiones para versiones válidas
¡Ganancia!
El secreto generalmente se está creando una vez durante el proceso de activación en un panel de control del usuario. Por lo tanto, todo lo que necesita hacer allí es mostrarlo al usuario de manera conveniente, como una cadena de texto y código QR, por ejemplo, y guardarlo en algún lugar con los datos del usuario.
use chillerlan Authenticator { Authenticator , AuthenticatorOptions };
$ options = new AuthenticatorOptions ;
$ options -> secret_length = 32 ;
$ authenticator = new Authenticator ( $ options );
// create a secret (stored somewhere in a *safe* place on the server. safe... hahaha jk)
$ secret = $ authenticator -> createSecret ();
// you can also specify the length of the secret key, which overrides the options setting
$ secret = $ authenticator -> createSecret ( 20 );
// set an existing secret
$ authenticator -> setSecret ( $ secret ); Un secreto creado con Authenticator::createSecret() también se almacenará internamente, para que no necesite proporcionar el secreto que acaba de crear en las operaciones de seguimiento con la instancia actual.
Ahora, durante el proceso de inicio de sesión, después de que el usuario haya ingresado con éxito sus credenciales, les pediría un código único para verificarlo en el secreto de su base de datos de usuario.
// verify the code
if ( $ authenticator -> verify ( $ otp )){
// that's it - 2FA has never been easier! :D
}Verificar códigos adyacentes
// try the first adjacent
$ authenticator -> verify ( $ otp , time () - $ options -> period ); // -> true
// try the second adjacent, default is 1
$ authenticator -> verify ( $ otp , time () + 2 * $ options -> period ); // -> false
// allow 2 adjacent codes
$ options -> adjacent = 2 ;
$ authenticator -> verify ( $ otp , time () + 2 * $ options -> period ); // -> true // switch mode to HOTP
$ options -> mode = AuthenticatorInterface:: HOTP ;
// user sends the OTP for code #42, which is equivalent to
$ otp = $ authenticator -> code ( 42 ); // -> 123456
// verify [123456, 42]
$ authenticator -> verify ( $ otp , $ counterValueFromUserDatabase ) // -> true Para mostrar un código QR para un autenticador móvil, necesitará un otpauth:// URI, que se puede crear utilizando el siguiente método.
$label debe ser algo que identifique la cuenta a la que pertenece el secreto$issuer es el nombre de su sitio web o empresa, por ejemplo, para que el usuario pueda identificar múltiples cuentas. $ uri = $ authenticator -> getUri ( $ label , $ issuer );
// -> otpauth://totp/my%20label?secret=NKSOQG7UKKID4IXW&issuer=chillerlan.net&digits=6&period=30&algorithm=SHA1 Tenga en cuenta que varias configuraciones de URI no son (todavía) reconocidas por todos los autenticadores. Consulte la wiki de Google Authenticator para obtener más información.
// code length, currently 6 or 8
$ options -> digits = 8 ;
// valid period between 15 and 60 seconds
$ options -> period = 45 ;
// set the HMAC hash algorithm
$ options -> algorithm = AuthenticatorInterface:: ALGO_SHA512 ;Authenticator| método | devolver | descripción |
|---|---|---|
__construct(SettingsContainerInterface $options = null, string $secret = null) | - | |
setOptions(SettingsContainerInterface $options) | Authenticator | llamado internamente por __construct() |
setSecret(string $secret) | Authenticator | llamado internamente por __construct() |
getSecret() | string | |
createSecret(int $length = null) | string | $length la configuración AuthenticatorOptions |
code(int $data = null) | string | $data pueden ser una marca de tiempo UNIX (TOTP) o un valor de contador (HOTP) |
verify(string $otp, int $data = null) | bool | Para $data consulte Authenticator::code() |
getUri(string $label, string $issuer, int $hotpCounter = null, bool $omitSettings = null) | string |
AuthenticatorOptions | propiedad | tipo | por defecto | permitido | descripción |
|---|---|---|---|---|
$digits | int | 6 | 6 u 8 | Longitud del código de autenticación |
$period | int | 30 | 15 - 60 | Período de validación (segundos) |
$secret_length | int | 20 | > = 16 | Longitud de la frase secreta (bytes, binario no codificado) |
$algorithm | string | SHA1 | SHA1 , SHA256 o SHA512 | Algoritmo de hash HMAC, ver AuthenticatorInterface::HASH_ALGOS |
$mode | string | totp | totp , hotp , battlenet o steam | Modo de autenticador: tiempo o contador basado, ver AuthenticatorInterface::MODES |
$adjacent | int | 1 | > = 0 | Número de códigos adyacentes permitidos |
$time_offset | int | 0 | * | Compensación de tiempo fija que se agregará al valor de tiempo actual |
$useLocalTime | bool | verdadero | * | si usar la hora local o solicitar la hora del servidor |
$forceTimeRefresh | bool | FALSO | * | si forzar el tiempo refrescante del servidor en cada llamada |
AuthenticatorInterface | método | devolver | descripción |
|---|---|---|
setOptions(SettingsContainerInterface $options) | AuthenticatorInterface | |
setSecret(string $encodedSecret) | AuthenticatorInterface | |
getSecret() | string | |
createSecret(int $length = null) | string | |
getServertime() | int | |
getCounter(int $data = null) | int | interno |
getHMAC(int $counter) | string | interno |
getCode(string $hmac) | int | interno |
getOTP(int $code) | string | interno |
code(int $data = null) | string | |
verify(string $otp, int $data = null) | bool |
| constante | tipo | descripción |
|---|---|---|
TOTP | string | |
HOTP | string | |
STEAM_GUARD | string | |
ALGO_SHA1 | string | |
ALGO_SHA256 | string | |
ALGO_SHA512 | string | |
MODES | array | Mapa del modo -> nombre de clase |
HASH_ALGOS | array | Lista de algoritmos de hash disponibles |