본문 바로가기
Q&A2024년 7월 22일1분 읽기

TOTP 2FA를 직접 구현하기

허
허진우
조회 695댓글 3

Google Authenticator 같은 TOTP 2FA를 직접 구현하는 방법을 알려주세요.

댓글 3

김김영삼2년 전

Node.js에서 TOTP 구현:

npm install otpauth qrcode

// 시크릿 생성
import { TOTP } from "otpauth";
const totp = new TOTP({ issuer: "MyApp", label: "user@email.com", algorithm: "SHA1", digits: 6, period: 30 });
const secret = totp.secret.base32; // DB에 저장
const uri = totp.toString(); // QR 코드용 URI

// QR 코드 생성
import QRCode from "qrcode";
const qr = await QRCode.toDataURL(uri);

// 검증
const isValid = totp.validate({ token: userInput, window: 1 }) !== null;
허허진우(guest)2년 전
복구 코드(Recovery Code)도 같이 구현해야 하나요?
김김영삼2년 전

네, 반드시 구현하세요. 사용자가 폰을 잃어버리면 로그인이 불가능합니다.

// 복구 코드 생성 (8개)
import crypto from "crypto";
const codes = Array.from({length: 8}, () =>
crypto.randomBytes(4).toString("hex")
); // ["a1b2c3d4", "e5f6g7h8", ...]
// 해시해서 DB 저장, 사용자에게 평문 보여주기
// 사용 시 해당 코드 삭제 (일회용)
Ctrl+Enter로 등록