Node.js에서 SMS 인증 API 5분 만에 연동하기 - 회원가입부터 로그인까지
Node.js에서 SMS 인증 API를 5분 만에 연동하는 방법을 단계별로 안내합니다. Express 서버 구성부터 회원가입 플로우 통합, 보안 베스트 프랙티스까지 실전 코드와 함께 알아보세요.
2026-02-23T03:34:18.818Z
const EASYAUTH_BASE_URL = 'https://easy-auth.compounding.co.kr/api'; const API_KEY = process.env.EASYAUTH_API_KEY;
/**
-
SMS 인증 코드 발송
-
@param {string} phoneNumber - 수신자 전화번호 (예: '01012345678')
-
@returns {Promise<object>} 발송 결과 */ async function sendVerificationCode(phoneNumber) { try { const response = await axios.post(
${EASYAUTH_BASE_URL}/v1/sms/send, { phoneNumber: phoneNumber, }, { headers: { 'Authorization':Bearer ${API_KEY}, 'Content-Type': 'application/json', }, } );console.log('인증 코드 발송 성공:', response.data); return response.data; } catch (error) { console.error('인증 코드 발송 실패:', error.response?.data || error.message); throw error; } }</code></pre><h2>2단계: 인증 코드 검증 구현</h2><p>사용자가 입력한 인증 코드를 검증하는 기능을 추가합니다.</p><pre><code>/**
-
SMS 인증 코드 검증
-
@param {string} phoneNumber - 전화번호
-
@param {string} code - 사용자가 입력한 인증 코드
-
@returns {Promise<object>} 검증 결과 */ async function verifyCode(phoneNumber, code) { try { const response = await axios.post(
${EASYAUTH_BASE_URL}/v1/sms/verify, { phoneNumber: phoneNumber, code: code, }, { headers: { 'Authorization':Bearer ${API_KEY}, 'Content-Type': 'application/json', }, } );console.log('인증 성공:', response.data); return response.data; } catch (error) { console.error('인증 실패:', error.response?.data || error.message); throw error; } }
module.exports = { sendVerificationCode, verifyCode };</code></pre><h2>3단계: Express API 서버 구성</h2><p>이제 위 함수들을 Express 서버의 API 엔드포인트로 연결합니다.</p><pre><code>// server.js const express = require('express'); const { sendVerificationCode, verifyCode } = require('./smsAuth'); require('dotenv').config();
const app = express(); app.use(express.json());
// 인증 코드 발송 엔드포인트 app.post('/api/auth/send-code', async (req, res) => { const { phoneNumber } = req.body;
if (!phoneNumber) { return res.status(400).json({ success: false, message: '전화번호를 입력해주세요.', }); }
// 전화번호 형식 검증 const phoneRegex = /^01[0-9]{8,9}$/; if (!phoneRegex.test(phoneNumber)) { return res.status(400).json({ success: false, message: '올바른 전화번호 형식이 아닙니다.', }); }
try { const result = await sendVerificationCode(phoneNumber); res.json({ success: true, message: '인증 코드가 발송되었습니다.', data: result }); } catch (error) { res.status(500).json({ success: false, message: '인증 코드 발송에 실패했습니다.' }); } });
// 인증 코드 검증 엔드포인트 app.post('/api/auth/verify-code', async (req, res) => { const { phoneNumber, code } = req.body;
if (!phoneNumber || !code) { return res.status(400).json({ success: false, message: '전화번호와 인증 코드를 모두 입력해주세요.', }); }
try { const result = await verifyCode(phoneNumber, code); res.json({ success: true, message: '인증이 완료되었습니다.', data: result }); } catch (error) { res.status(400).json({ success: false, message: '인증 코드가 올바르지 않습니다.' }); } });
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(서버가 포트 ${PORT}에서 실행 중입니다.);
});</code></pre><h2>4단계: 회원가입 플로우에 SMS 인증 통합</h2><p>실제 회원가입 프로세스에 SMS 인증을 통합하는 예제입니다.</p><pre><code>// 회원가입 엔드포인트 (SMS 인증 통합)
app.post('/api/auth/register', async (req, res) => {
const { email, password, phoneNumber, verificationCode } = req.body;
// 1. 입력값 검증 if (!email || !password || !phoneNumber || !verificationCode) { return res.status(400).json({ success: false, message: '모든 필드를 입력해주세요.', }); }
try { // 2. SMS 인증 코드 검증 const verifyResult = await verifyCode(phoneNumber, verificationCode);
if (!verifyResult.verified) {
return res.status(400).json({
success: false,
message: '전화번호 인증에 실패했습니다.',
});
}
// 3. 사용자 생성 (데이터베이스 저장 로직)
// const user = await createUser({ email, password, phoneNumber });
res.status(201).json({
success: true,
message: '회원가입이 완료되었습니다.',
});
} catch (error) { res.status(500).json({ success: false, message: '회원가입 처리 중 오류가 발생했습니다.', }); } });</code></pre><h2>보안 베스트 프랙티스</h2><p>SMS 인증을 구현할 때 반드시 고려해야 할 보안 사항들입니다:</p><ul><li><strong>Rate Limiting 적용:</strong> 동일 번호로 반복 요청을 방지하기 위해 시간당 발송 횟수를 제한하세요.</li><li><strong>인증 코드 만료 시간:</strong> 일반적으로 3~5분으로 설정합니다. 너무 길면 보안에 취약하고, 너무 짧으면 사용자 경험이 나빠집니다.</li><li><strong>시도 횟수 제한:</strong> 인증 코드 입력 시도를 5회 이내로 제한하여 무차별 대입 공격을 방지하세요.</li><li><strong>HTTPS 필수:</strong> API 통신 시 반드시 HTTPS를 사용하여 데이터를 암호화하세요.</li><li><strong>API 키 보호:</strong> API 키를 환경 변수로 관리하고, 클라이언트 코드에 절대 노출하지 마세요.</li></ul><blockquote><p><strong>Tip:</strong> EasyAuth는 자체적으로 Rate Limiting과 인증 코드 만료 관리를 지원하므로, 서버 측에서 추가 로직을 최소화할 수 있습니다.</p></blockquote><h2>테스트하기</h2><p>서버를 실행하고 cURL 또는 Postman으로 테스트해 보세요:</p><pre><code># 서버 실행 node server.js
인증 코드 발송 테스트
curl -X POST http://localhost:3000/api/auth/send-code
-H "Content-Type: application/json"
-d '{"phoneNumber": "01012345678"}'
인증 코드 검증 테스트
curl -X POST http://localhost:3000/api/auth/verify-code
-H "Content-Type: application/json"
-d '{"phoneNumber": "01012345678", "code": "123456"}'</code></pre><h2>마무리</h2><p>이 가이드를 통해 Node.js 프로젝트에 SMS 인증 기능을 빠르게 연동하는 방법을 알아보았습니다. <a href="https://easy-auth.compounding.co.kr" target="_blank">EasyAuth</a>를 사용하면 복잡한 계약 절차 없이 건당 25원이라는 합리적인 비용으로 SMS 인증을 구현할 수 있습니다. 가입 시 10건 무료 제공되니 부담 없이 테스트해 보세요.</p><p>더 자세한 API 스펙은 <a href="https://easy-auth.compounding.co.kr/docs" target="_blank">EasyAuth API 문서</a>에서 확인할 수 있습니다. 다음 글에서는 React 프론트엔드에서 SMS 인증 UI를 구현하는 방법을 다루겠습니다.</p>
비트베이크에서 광고를 시작해보세요
광고 문의하기