Способы реализации двухфакторной аутентификации на PHP с примерами кода

Вот несколько методов реализации двухфакторной аутентификации (2FA) в PHP, а также примеры кода:

  1. Одноразовый пароль на основе времени (TOTP) с использованием Google Authenticator:

    // Install the "robthree/twofactorauth" library using Composer
    require_once 'vendor/autoload.php';
    use RobThree\Auth\TwoFactorAuth;
    $secret = 'your_secret_key';
    $totp = new TwoFactorAuth('YourApp');
    $qrCodeUrl = $totp->getQRCodeImageAsDataUri('YourApp:username', $secret);
    // Verify the code
    $code = $_POST['code'];
    $isValid = $totp->verifyCode($secret, $code);
    if ($isValid) {
    // Code is valid, proceed with authentication
    } else {
    // Code is invalid, show error message
    }
  2. Подтверждение по SMS с использованием Twilio:

    // Install the "twilio/sdk" library using Composer
    require_once 'vendor/autoload.php';
    use Twilio\Rest\Client;
    $accountSid = 'your_account_sid';
    $authToken = 'your_auth_token';
    $client = new Client($accountSid, $authToken);
    $verification = $client->verify->v2->services('your_service_sid')
    ->verifications
    ->create(['to' => '+1234567890', 'channel' => 'sms']);
    // Verify the code
    $code = $_POST['code'];
    $isValid = $client->verify->v2->services('your_service_sid')
    ->verificationChecks
    ->create(['to' => '+1234567890', 'code' => $code]);
    if ($isValid->valid) {
    // Code is valid, proceed with authentication
    } else {
    // Code is invalid, show error message
    }
  3. Подтверждение по электронной почте с помощью PHPMailer:

    // Install the "phpmailer/phpmailer" library using Composer
    require_once 'vendor/autoload.php';
    use PHPMailer\PHPMailer\PHPMailer;
    $mail = new PHPMailer();
    $mail->isSMTP();
    $mail->Host = 'smtp.example.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'your_username';
    $mail->Password = 'your_password';
    $mail->SMTPSecure = 'tls';
    $mail->Port = 587;
    $mail->setFrom('from@example.com', 'Your Name');
    $mail->addAddress('to@example.com', 'Recipient Name');
    $mail->Subject = 'Two-Factor Authentication';
    $mail->Body = 'Your verification code is: 123456';
    // Send the email
    if ($mail->send()) {
    // Code sent successfully, proceed with authentication
    } else {
    // Error sending the code, show error message
    }