Firebase 서비스(Firestore, Storage, Realtime Database)에 접근할 때
누가, 어떤 데이터에, 어떤 행동을 할 수 있는지 규칙으로 정의하는 것.
클라이언트 코드에서 막는 게 아니라 서버 레벨에서 차단하기 때문에
악의적인 요청도 Rules에서 걸러짐.
Firebase 콘솔 → Firestore → 규칙 탭에서 작성.
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{컬렉션}/{문서ID} {
allow read, write: if 조건;
}
}
}
// 누구나 읽기 가능
allow read: if true;
// 로그인한 사용자만
allow read, write: if request.auth != null;
// 본인 문서만 읽기
allow read: if request.auth.uid == resource.data.uid;
// 본인 문서만 수정/삭제
allow update, delete: if request.auth.uid == resource.data.uid;
// 본인 uid로만 생성 (파라미터 변조 방지)
allow create: if request.auth.uid == request.resource.data.uid;
| 설명 | |
|---|---|
request.auth | 현재 요청한 사용자 정보 |
request.resource.data | 요청으로 쓰려는 데이터 (create/update 시) |
resource.data | Firestore에 이미 저장된 데이터 (read/update/delete 시) |
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /posts/{postId} {
allow read: if true; // 누구나 읽기
allow create: if request.auth.uid == request.resource.data.uid; // 본인 uid로만 등록
allow update, delete: if request.auth.uid == resource.data.uid; // 본인 글만 수정/삭제
}
}
}
이미지, 파일 업로드/다운로드 권한 제어.
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if 조건;
}
}
}
// 로그인한 사용자만 업로드
allow write: if request.auth != null;
// 누구나 다운로드, 로그인한 사람만 업로드
allow read: if true;
allow write: if request.auth != null;
// 본인 폴더에만 업로드 (경로로 uid 검증)
match /users/{userId}/{allPaths=**} {
allow read, write: if request.auth.uid == userId;
}
// 파일 크기 제한 (5MB 이하)
allow write: if request.resource.size < 5 * 1024 * 1024;
// 이미지 파일만 허용
allow write: if request.resource.contentType.matches('image/.*');
{
"rules": {
".read": "auth != null",
".write": "auth != null",
"users": {
"$uid": {
".read": "$uid === auth.uid",
".write": "$uid === auth.uid"
}
}
}
}
$uid — 경로의 와일드카드 변수auth.uid — 현재 로그인한 사용자 uidFirebase 콘솔에서 Rules Playground 활용.
실제 배포 전에 시뮬레이션으로 규칙이 의도대로 동작하는지 확인 가능.
// 위험 — 모든 접근 허용 (개발 초기에 임시로 쓰다가 그대로 배포하는 경우)
allow read, write: if true;
→ 배포 전 반드시 Rules 점검 필요. 기본값은 항상 거부(false)로 시작하는 게 안전.
Rules는 클라이언트에서 막는 게 아니라 서버에서 막는 거라 빠뜨리면 진짜 위험함.
request.resource.data(쓰려는 값)와 resource.data(이미 있는 값) 구분이 헷갈렸는데
create/update/delete 상황별로 어떤 게 쓰이는지 외워두는 게 편할 것 같음.