Um gerador para contador (RFC 4226) e baseado em tempo (RFC 6238) Senhas de vez em que se senhas (OTP). (AKA mais uma implementação do Google Authenticator!)
ext-curl para sincronização do tempo do servidor de guarda Steamext-sodium para implementações constantes de tempo da base64 Encodes/decodificar e hex2bin/bin2hex ( paragonie/constant_time_encoding é usado como fallback) requer compositor
via terminal: composer require chillerlan/php-authenticator
composer.json
{
"require" : {
"php" : " ^8.2 " ,
"chillerlan/php-authenticator" : " dev-main "
}
} Nota: Substitua dev-main por uma restrição de versão, por exemplo ^5.0 - consulte Releases para versões válidas
Lucro!
O segredo geralmente está sendo criado uma vez durante o processo de ativação em um painel de controle do usuário. Então, tudo o que você precisa fazer é exibi -lo ao usuário de uma maneira conveniente - como uma string de texto e código QR, por exemplo - e salvá -lo em algum lugar com os dados do usuário.
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 ); Um segredo criado com Authenticator::createSecret() também será armazenado internamente, para que você não precise fornecer o segredo que acabou de criar nas operações de acompanhamento com a instância atual.
Agora, durante o processo de login - depois que o usuário inseriu com êxito suas credenciais -, você solicitaria um código único para verificar no segredo do banco de dados do usuário.
// verify the code
if ( $ authenticator -> verify ( $ otp )){
// that's it - 2FA has never been easier! :D
}Verifique os códigos adjacentes
// 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 exibir um código QR para um autenticador móvel, você precisará de um otpauth:// URI, que pode ser criado usando o seguinte método.
$label deve ser algo que identifica a conta à qual o segredo pertence$issuer é o nome do seu site ou empresa, por exemplo, para que o usuário possa identificar várias contas. $ uri = $ authenticator -> getUri ( $ label , $ issuer );
// -> otpauth://totp/my%20label?secret=NKSOQG7UKKID4IXW&issuer=chillerlan.net&digits=6&period=30&algorithm=SHA1 Lembre -se de que várias configurações de URI ainda não são reconhecidas por todos os autenticadores. Verifique o Google Authenticator Wiki para obter mais informações.
// 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 | retornar | descrição |
|---|---|---|
__construct(SettingsContainerInterface $options = null, string $secret = null) | - | |
setOptions(SettingsContainerInterface $options) | Authenticator | chamado internamente por __construct() |
setSecret(string $secret) | Authenticator | chamado internamente por __construct() |
getSecret() | string | |
createSecret(int $length = null) | string | $length Substituir a configuração AuthenticatorOptions |
code(int $data = null) | string | $data podem ser um timestamp UNIX (TOTP) ou um 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 | propriedade | tipo | padrão | permitido | descrição |
|---|---|---|---|---|
$digits | int | 6 | 6 ou 8 | Comprimento do código de autenticação |
$period | int | 30 | 15 - 60 | Período de validação (segundos) |
$secret_length | int | 20 | > = 16 | comprimento da frase secreta (bytes, binário não codificado) |
$algorithm | string | SHA1 | SHA1 , SHA256 ou SHA512 | Algoritmo HMAC Hash, consulte AuthenticatorInterface::HASH_ALGOS |
$mode | string | totp | totp , hotp , battlenet ou steam | Modo de autenticador: baseado em tempo ou contador, consulte AuthenticatorInterface::MODES |
$adjacent | int | 1 | > = 0 | Número de códigos adjacentes permitidos |
$time_offset | int | 0 | * | O deslocamento de tempo fixo que será adicionado ao valor de tempo atual |
$useLocalTime | bool | verdadeiro | * | se deve usar a hora local ou solicitar o horário do servidor |
$forceTimeRefresh | bool | falso | * | Se deve forçar o tempo de refrescante em cada chamada |
AuthenticatorInterface | método | retornar | descrição |
|---|---|---|
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 | descrição |
|---|---|---|
TOTP | string | |
HOTP | string | |
STEAM_GUARD | string | |
ALGO_SHA1 | string | |
ALGO_SHA256 | string | |
ALGO_SHA512 | string | |
MODES | array | Mapa do modo -> ClassName |
HASH_ALGOS | array | Lista de algoritmos de hash disponíveis |