가장 먼저 Google reCAPTCHA 관리자 페이지에서 발급받은 ReCAPTCHA v3용 Site Key를 준비한다.
이 키는 프론트엔드에서 사용이 되어진다.
VITE_RECAPTCHA_SITE_KEY=6LdTXC0sAAAAAJ4FEPGTKa1QZ04dOOL8VJIK102b
ReCAPTCHA 적용 컴포넌트는 다음과 같이 구현할 수 있다.
useEffect 훅을 사용하여 ReCAPTCHA 스크립트를 동적으로 로드하고,
grecaptcha.execute를 통해 토큰을 받아온다.
const RECAPTCHA_SITE_KEY = import.meta.env.VITE_RECAPTCHA_SITE_KEY;
const RecaptchaPage = () => {
// recaptcha가 준비되었는지 상태를 관리하는 ref
const recaptchaReady = useRef(false);
// ReCAPTCHA 스크립트를 동적으로 로드하는 useEffect
useEffect(() => {
const scriptId = "recaptcha-script";
const existingScript = document.getElementById(scriptId);
if (existingScript) {
if (window.grecaptcha && window.grecaptcha.ready) {
window.grecaptcha.ready(() => {
console.log("ReCAPTCHA ready (cached script).");
recaptchaReady.current = true;
});
}
return;
}
const script = document.createElement("script");
script.id = scriptId;
script.src = `https://www.google.com/recaptcha/api.js?render=${RECAPTCHA_SITE_KEY}`;
script.async = true;
script.defer = true;
document.body.appendChild(script);
script.onload = () => {
if (window.grecaptcha) {
window.grecaptcha.ready(() => {
recaptchaReady.current = true;
});
}
};
}, []);
// 비밀번호 변경 요청 함수
const onClickSubmit = async (e) => {
e.preventDefault();
setMessage(""); // 메시지 초기화
setLoading(true);
// 클라이언트 측 유효성 검사
if (!newPassword1 || !newPassword2) {
setMessage("모든 비밀번호 필드를 입력해주세요.");
setLoading(false);
return;
}
if (newPassword1 !== newPassword2) {
setMessage("비밀번호가 일치하지 않습니다.");
setLoading(false);
return;
}
try {
if (!window.grecaptcha) {
throw new Error("Recaptcha 객체가 로드되지 않았습니다.");
}
// ReCAPTCHA API가 아직 준비되지 않았다면 사용자에게 알리고 재시도를 유도합니다.
if (!recaptchaReady.current) {
setMessage(
"보안 인증(ReCAPTCHA) 서비스 준비 중입니다. 잠시 후 다시 시도해주세요."
);
setLoading(false);
return;
}
// reCAPTCHA 객체와 execute 메서드 존재 여부 최종 확인
if (!window.grecaptcha) {
throw new Error("Recaptcha 객체가 로드되지 않았습니다.");
}
// 2. ready 함수 안에서 execute 실행 (Promise로 감싸서 처리)
const recaptchaToken = await new Promise((resolve, reject) => {
window.grecaptcha.ready(async () => {
try {
const token = await window.grecaptcha.execute(
RECAPTCHA_SITE_KEY,
{
action: "change_password",
}
);
resolve(token);
} catch (err) {
// 여기서 "No clients" 등의 구체적인 에러가 잡힘
reject(err);
}
});
});
// 백엔드로 보낼 데이터 객체 구성
const requestBody = {
username,
email,
provider: "local",
changePassword1: newPassword1,
changePassword2: newPassword2,
recaptchaResponse: recaptchaToken,
};
// 백엔드 API 호출
const response = await axios.put(
API_ENDPOINTS.AUTH.CHANGE_PWD,
requestBody,
{
headers: {
"Content-Type": "application/json",
},
}
);
// 요청 성공 시
nav("/result/password", { replace: true });
} catch (error) {
console.error("비밀번호 변경 오류: ", error);
if (axios.isAxiosError(error) && error.response) {
setMessage(
`오류: ${
error.response.data.message ||
error.response.data ||
"서버 응답 오류"
}`
);
} else {
setMessage(
`오류: ${
error.message || "알 수 없는 오류가 발생했습니다."
}`
);
}
} finally {
setLoading(false);
}
};
// ...
}
[] 의존성 배열)