Authentication Methods
วิธีการยืนยันตัวตนมีหลายรูปแบบ แต่ละแบบมีข้อดีและข้อเสียต่างกัน เราจะมาดูวิธีการที่นิยมใช้กัน
1. Username/Password Authentication
วิธีพื้นฐานที่สุดคือการใช้ username และ password โดยต้องมีการเข้ารหัสข้อมูลที่ปลอดภัย
javascript
// Hash password before storing
import bcrypt from 'bcrypt';
async function hashPassword(password) {
const salt = await bcrypt.genSalt(10);
return bcrypt.hash(password, salt);
}
async function verifyPassword(password, hashedPassword) {
return bcrypt.compare(password, hashedPassword);
}
2. Social Authentication
การใช้บัญชีจาก social platform เช่น Google, Facebook, GitHub ในการยืนยันตัวตน
javascript
// Using NextAuth.js example
import NextAuth from 'next-auth';
import GoogleProvider from 'next-auth/providers/google';
export default NextAuth({
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_ID,
clientSecret: process.env.GOOGLE_SECRET,
}),
],
});
3. Biometric Authentication
การยืนยันตัวตนด้วยข้อมูลทางชีวภาพ เช่น ลายนิ้วมือ, ใบหน้า
javascript
// Web Authentication API example
async function authenticateWithBiometric() {
try {
const credential = await navigator.credentials.create({
publicKey: {
challenge: new Uint8Array(32),
rp: { name: 'Your App' },
user: {
id: new Uint8Array(16),
name: '[email protected]',
displayName: 'User Name'
},
pubKeyCredParams: [{alg: -7, type: 'public-key'}]
}
});
return credential;
} catch (err) {
console.error('Biometric auth failed:', err);
}
}
4. Multi-factor Authentication (MFA)
การยืนยันตัวตนหลายขั้นตอน เพื่อเพิ่มความปลอดภัย
javascript
// TOTP (Time-based One-Time Password) example
import { authenticator } from 'otplib';
function setupMFA(userId) {
const secret = authenticator.generateSecret();
const otpauth = authenticator.keyuri(
userId,
'YourApp',
secret
);
return { secret, otpauth };
}
function verifyToken(token, secret) {
return authenticator.verify({ token, secret });
}