ตัวอย่างโปรแกรมด้านล่างเป็นการรองรับการลงชื่อเช้าใช้แอพพลิเคชั่นในแบบ 2 factor authenticator (2FA) โดยผู้ใช้งานจะต้องระบชื่อผู้ใช้และรหัสผ่าน จากนั้นจะต้องแสกน QR Code เพื่อยืนยันตัวตนด้วยโทรศัพท์มือถืออีกครั้งจึงจะยอมให้เข้าระบบๆได้
ในตัวอย่างนี้เมธอด authentication เป็นเมธอดที่เราต้องกำนดตรรกะในการตรวจสอบชื่อและรหัสผ่านของผู้ใช้งาน เมธอด generateCode เป็นเมธอดที่ใช้สร้างรหัสผ่านเฉพาะสำหรับแต่ละครั้งในการใช้งานเพื่อนำไปสร้าง QR Code ด้วยเมธอด generateQRCode และเมธอด validateCode เป็นเมธอดที่ใช้ตรวจสอบความถูกต้องของการแสกน
ตัวอย่างโปรแกรม
import java.util.Scanner;
import java.util.UUID;
public class TwoFactorAuth {
public static void main(String[] args) {
// Simulating user login with user ID and password
Scanner scanner = new Scanner(System.in);
System.out.println("Enter user ID: ");
String userId = scanner.nextLine();
System.out.println("Enter password: ");
String password = scanner.nextLine();
if (authenticate(userId, password)) {
System.out.println("Login successful!");
// Generating a unique code for the QR code
String code = generateCode();
// Generating the QR code using the code
String qrCodeUrl = generateQRCode(code);
// Displaying the QR code URL to the user
System.out.println("Scan this QR code with your mobile device:");
System.out.println(qrCodeUrl);
// Waiting for the user to scan the QR code and enter the code
System.out.println("Enter the code displayed on your mobile device:");
String inputCode = scanner.nextLine();
if (validateCode(code, inputCode)) {
System.out.println("Two-factor authentication successful!");
} else {
System.out.println("Invalid code, please try again.");
}
} else {
System.out.println("Invalid credentials, please try again.");
}
}
// Method to authenticate the user using user ID and password
public static boolean authenticate(String userId, String password) {
// Your authentication logic here
return true;
}
// Method to generate a unique code for the QR code
public static String generateCode() {
return UUID.randomUUID().toString();
}
// Method to generate the QR code using the code
public static String generateQRCode(String code) {
// Your QR code generation logic here
return “https://example.com/qrcode/” + code;
}
// Method to validate the code entered by the user
public static boolean validateCode(String expectedCode, String inputCode) {
return expectedCode.equals(inputCode);
}
}