이메일/비밀번호 가입과 로그인, Google 소셜 로그인, 로그인 상태 추적과 로그아웃을 구현한다.
Authentication
Firebase Authentication은 회원가입, 로그인, 소셜 로그인을 직접 서버를 만들지 않고도 처리할 수 있게 해줍니다. 비밀번호 해싱이나 토큰 관리 같은 까다로운 부분을 Firebase가 대신 처리해 줍니다. 이번 강의에서는 가장 많이 쓰이는 인증 흐름을 구현해 봅니다.
학습 목표
- 이메일/비밀번호로 가입하고 로그인한다.
- Google 소셜 로그인을 연동한다.
onAuthStateChanged로 로그인 상태를 추적한다.- 로그아웃과 현재 사용자 정보를 다룬다.
이메일/비밀번호 가입
콘솔의 Authentication → "로그인 방법"에서 이메일/비밀번호 제공업체를 먼저 활성화해야 합니다. 그다음 createUserWithEmailAndPassword로 새 계정을 만듭니다.
import { createUserWithEmailAndPassword } from 'firebase/auth';
import { auth } from '@/lib/firebase';
async function signUp(email: string, password: string) {
const cred = await createUserWithEmailAndPassword(auth, email, password);
console.log('가입 완료:', cred.user.uid);
return cred.user;
}
로그인
이미 가입된 계정은 signInWithEmailAndPassword로 로그인합니다.
import { signInWithEmailAndPassword } from 'firebase/auth';
import { auth } from '@/lib/firebase';
async function login(email: string, password: string) {
const cred = await signInWithEmailAndPassword(auth, email, password);
return cred.user;
}
Google 소셜 로그인
GoogleAuthProvider와 signInWithPopup을 사용하면 팝업으로 Google 계정 로그인을 처리할 수 있습니다. 콘솔에서 Google 제공업체를 먼저 활성화해야 합니다.
import { GoogleAuthProvider, signInWithPopup } from 'firebase/auth';
import { auth } from '@/lib/firebase';
const provider = new GoogleAuthProvider();
async function loginWithGoogle() {
const cred = await signInWithPopup(auth, provider);
return cred.user;
}
💡 TIP — 모바일 환경에서는 팝업이 차단될 수 있어
signInWithRedirect가 더 안정적입니다. 상황에 맞게 선택하세요.
로그인 상태 추적
onAuthStateChanged는 로그인 상태가 바뀔 때마다 호출됩니다. 앱이 처음 로드될 때 현재 사용자를 복원하는 데도 쓰입니다.
import { onAuthStateChanged, type User } from 'firebase/auth';
import { auth } from '@/lib/firebase';
const unsubscribe = onAuthStateChanged(auth, (user: User | null) => {
if (user) {
console.log('로그인됨:', user.email);
} else {
console.log('로그아웃 상태');
}
});
// 컴포넌트 언마운트 시 구독 해제
unsubscribe();
⚠️ 주의 —
auth.currentUser는 앱 초기화 직후에는 아직null일 수 있습니다. 사용자 정보가 필요하면onAuthStateChanged콜백 안에서 확인하는 것이 안전합니다.
로그아웃과 현재 사용자
import { signOut } from 'firebase/auth';
import { auth } from '@/lib/firebase';
async function logout() {
await signOut(auth);
}
// 현재 로그인된 사용자
const user = auth.currentUser;
console.log(user?.uid, user?.email);
| 함수 | 역할 |
|---|---|
| createUserWithEmailAndPassword | 신규 가입 |
| signInWithEmailAndPassword | 이메일 로그인 |
| signInWithPopup | 소셜 로그인 |
| onAuthStateChanged | 상태 추적 |
| signOut | 로그아웃 |
요약
- 이메일 가입은
createUserWithEmailAndPassword, 로그인은signInWithEmailAndPassword를 씁니다. - Google 로그인은
GoogleAuthProvider와signInWithPopup으로 구현합니다. onAuthStateChanged로 로그인 상태 변화를 구독하고, 반환된 함수로 해제합니다.auth.currentUser로 현재 사용자를 조회하되, 초기화 타이밍에 주의합니다.- 콘솔에서 사용할 로그인 제공업체를 먼저 활성화해야 합니다.
연습문제
- 가입과 로그인 함수의 이름은 각각 무엇인가요?
onAuthStateChanged가 반환하는 값은 무엇이고 언제 사용하나요?signInWithPopup대신signInWithRedirect를 쓰는 상황은 언제인가요?- 앱 로드 직후
auth.currentUser가null인 경우 사용자를 어떻게 안전하게 확인하나요?
힌트 — 인증 상태는 비동기로 복원된다는 점을 떠올려 보세요.
💡 연습문제 풀이
불러오는 중…
댓글 0
“Firebase” 강좌에 대한 댓글입니다.