Swift2FA is a secure and easy-to-use PHP library for the fast implementation of two-factor authentication. It supports a variety of methods, including authentication via any authenticator app like Google Authenticator, via email using SMTP with PHPMailer, and now also supports SMS-based authentication using services like Twilio. Swift2FA boasts of:
- Easy integration
- High security
- Fast implementation
The library offers a smooth process for securing your application and ensuring users' accounts are well protected.
- Integration with Google Authenticator or other TOTP-based apps.
- Email-based authentication through SMTP with PHPMailer.
- SMS-based authentication using Twilio or other SMS services.
- Fast and simple setup.
- Strong encryption for securing secret keys using modern algorithms.
To install Swift2FA, follow these steps:
- Install dependencies via Composer:
composer require uthmandev/swift2fa
use Swift2FA\Swift2FA
$variable = new Swift2FA();
To use Swift2FA, you need to first encrypt the secret key that will be used for TOTP (Time-based One-Time Password) generation in two-factor authentication. The process involves two steps:
- Generate the Secret Key: The secret key is a random Base32 encoded value.
- Encrypt the Secret Key: This Base32 encoded key is then encrypted using AES-256 with an encryption key stored in an environment variable.
To encrypt a secret key, you can use the following code:
use Swift2FA\Swift2FA;
// Initialize the Swift2FA class
$variable = new Swift2FA();
// Encrypt the generated Base32 key
$encryptedKey = $variable->encryptKey();
This will return an encrypted secret key, which can be safely stored and used for TOTP generation.
Note
The Base32 encoded key is generated randomly within the Swift2FA
class.
The encryption is done using AES-256, and the encryption key should be securely stored in an environment variable for security purposes.
Make sure to handle the encryption key carefully and restrict access to your environment files to only trusted users.
Make sure to set the encryption key in your environment file (.env) like so:
ENCRYPTION_KEY=your-secure-encryption-key
The Swift2FA class will automatically access the ENCRYPTION_KEY environment variable during the encryption process. You do not need to manually retrieve it in your code.
- Generate a random Base32 encoded secret key.
- Encrypt the key using Swift2FA and an AES-256 encryption method.
- Store the encrypted key securely.
Decrypting the secret key first is crucial before generating the TOTP. The encrypted secret key needs to be decrypted using the appropriate encryption key.
use Swift2FA\Swift2FA;
// Initialize the Swift2FA instance
$variable = new Swift2FA();
// Decrypt the encrypted key
$decryptKey = $variable->decryptKey($encryptedKey);
The decryptKey method takes an argument of the encrypted data and will decrypt the encrypted data using the encryption key. ###$ Key Points:
-
decryptKey($encryptedKey): This method decrypts the encrypted secret key using the encryption key within the class.
-
The decrypted key can then be used for generating the TOTP.
Generating TOTP (Time-based One-Time Password) can be done in Swift2FA using the generateTOTP
method. The TOTP uses the HMAC algorithm to generate a code that is only valid for a specific period of time.
The time step (the validity duration of the code) and the length of the code are arguments that can be passed, but they are set to default values.
- $timeStep = 30 seconds
- $codeLength = 6 digit These are the standard settings for most authenticator apps.
use Swift2FA\Swift2FA;
// Initialize the Swift2FA instance
$variable = new Swift2FA();
// Generate TOTP code using the secret key
$TotpCode = $variable->generateTOTP($secret);
This will return a TOTP code that will be the same on the authenticator app, provided the same time step is used.
- HMAC Algorithm: TOTP uses the HMAC algorithm to generate the time-based code.
- Time Step: The period during which the code remains valid, defaulted to 30 seconds.
- Code Length: The length of the generated code, defaulted to 6 digits.
This method generates a scannable QR code for authenticator apps. This QR code takes arguments of the user's email (which is the user's email) and the secret (which will be used by the authenticator app to generate TOTP). It returns a QR image.
An app name is also required, and Swift2FA fetches it from the environment .env
file. Make sure to set it:
APP_NAME=swift2fa_app
The generated QR image can be styled with a default CSS class:
qrcode-image
$email
: The user's email address.$secret
: The user's decrypted secret.$appName
: The application name, fetched from the environment.
use Swift2FA\Swift2FA;
// Initialize the Swift2FA instance
$variable = new Swift2FA();
// User's email and decrypted secret
$email = '[email protected]';
$secret = 'user_decrypted_secret';
// Generate QR code using the user's email and secret
$Qr = $variable->generateQR($email, $secret);
Once a user scans the QR code, a TOTP (Time-based One-Time Password) link is generated. This link can be used with any OTP scanning app or authenticator. The app then generates the TOTP based on the secret embedded in the link.
The links (
otpauth://
) will not work when opened directly from a browser.
Browsers cannot process or redirectotpauth://
schemes to an authenticator app.The best method for adding TOTP to your authenticator apps is by scanning the QR code, as most authenticator apps are designed to work with QR codes.
use Swift2FA\Swift2FA;
// Initialize the Swift2FA instance
$variable = new Swift2FA();
// User's email and decrypted secret
$email = '[email protected]';
$secret = 'user_decrypted_secret';
// Generate the TOTP link
$result = $variable->generatelink($email, $secret);
// Display the TOTP Link
echo '<p><strong>TOTP Link:</strong> <a href="' . htmlspecialchars($result) . '">' . htmlspecialchars($result) . '</a></p>';
Swift2FA comes with an additional method for validating the TOTP code generated by the authenticator. This method compares the code generated with the secret key to check if it matches the one on the authenticator app.
- $input: The code entered by the user (the input code).
- $secretKey: The secret key used to generate the TOTP. This is compared with the code provided.
The method returns a boolean value, indicating whether the validation was successful.
use Swift2FA\Swift2FA;
// Initialize the Swift2FA instance
$variable = new Swift2FA();
// Validate the TOTP code entered by the user
$isValid = $variable->TOTPValidate($input, $secret);
- The method compares the code entered by the user with the one generated using the secret key.
- The result is a boolean value, true if the code matches, and false otherwise.
Validating TOTP sent through email will require a longer time step. Using this
TOTPValidate
Method will use a time step of 30, which is 30 seconds. For email-sent TOTP, use this way:
use Swift2FA\Swift2FA;
// Initialize the Swift2FA instance
$variable = new Swift2FA();
$timeStep = 120; // two minutes
$secret = $user_secret;
$input = 1244;
// Generate TOTP
$totpCode = $variable->generateTOTP($secret, $timeStep);
// Check if input and generated code are the same
if ($input === $totpCode) {
// Valid code, proceed
} else {
// Invalid code
}
To send the generated TOTP (Time-Based One-Time Password), Swift2FA uses PHPMailer for email delivery to the designated user. You can also use the same method to send the code via SMS using appropriate services like Twilio.
Before using the method to send TOTP, make sure to configure your environment variables to handle SMTP settings for sending emails.
HOST=smtp.gmail.com
USER_NAME=[email protected]
PASSWORD="yourGmailAppPassword"
PORT=465
SMTP_SECURE=ssl
The method used to send the TOTP accepts the following arguments:
$mailType
: Specifies the email service type, e.g., SMTP using PHPMailer.$email
: The recipient's email address.$message
: The message body, which will include the generated TOTP code.$name
: The name of the recipient (for personalized emails).$subject
(optional): The subject line of the email. If not provided, a default subject will be used.
Here is an example of how to use the method in your code:
use Swift2FA\Swift2FA;
// Initialize the Swift2FA instance
$swift2FA = new Swift2FA();
// Define the arguments for sending the TOTP
$mailType = 'SMTP'; // Specify the mail type (e.g., 'SMTP' using PHPMailer)
$email = '[email protected]'; // Recipient's email address
$message = 'Your TOTP code is: 123456'; // Message content with TOTP
$name = 'Recipient Name'; // Recipient's name
$subject = 'Your Authentication Code'; // Optional: email subject
// Send the code via email or SMS using the Swift2FA method
$swift2FA->Mail($mailType, $email, $message, $name, $subject);
Make sure to replace the environment variable placeholders (e.g., USER_NAME, PASSWORD) with actual values.
You can send the generated TOTP code via SMS using a service provider like Twilio. Follow the steps below to set up the environment and use the method to send the code.
Before sending the SMS, make sure to set up your environment variables with your Twilio account details:
TWILIO_SID=your_twilio_sid_here
TWILIO_AUTH_TOKEN=your_twilio_auth_token_here
TWILIO_PHONE_NUMBER=your_twilio_phone_number_here
The method to send the SMS takes the following arguments:
$phoneNumber
:The recipient's phone number to send the SMS.$messageBody
: The message content, which includes the generated TOTP code.$name
: The name of the recipient (for personalized messages).
Here’s an example of how to send the TOTP code via SMS using Twilio:
use Swift2FA\Swift2FA;
// Initialize the Swift2FA instance
$swift2FA = new Swift2FA();
// Define the arguments for sending the TOTP via SMS
$phoneNumber = '+1234567890'; // Recipient's phone number
$messageBody = 'Your TOTP code is: 123456'; // Message content with TOTP
$name = 'Recipient Name'; // Recipient's name
// Send the SMS using the Swift2FA method
$swift2FA->SMS($phoneNumber, $messageBody, $name);
i welcome all contributions! If you’d like to enhance this project, please fork the repository, make your changes, and create a pull request. Your contributions help make this project better!
This project is licensed under the MIT License. You are free to use, modify, and distribute the code as long as the original license is retained.
If you have any questions, suggestions, or inquiries, feel free to reach out:
- Website: dev-utman.vercel.app
- Email: [email protected]
Thank you for your interest in this project! If you find it useful, don’t forget to leave a 🌟star!