Cloud Storage용 Firebase 보안 규칙을 사용하면 Cloud Storage 버킷에 저장된 객체에 대한 액세스를 제어할 수 있습니다. 유연한 규칙 구문을 사용하면 Cloud Storage 버킷에 대한 모든 쓰기에서 특정 파일에 대한 작업에 이르기까지 모든 작업을 제어하는 규칙을 만들 수 있습니다.
이 가이드에서는 완전한 규칙 세트를 생성하기 위한 Cloud Storage 보안 규칙의 기본 구문과 구조를 설명합니다.
서비스 및 데이터베이스 선언
Cloud Storage에 대한 Firebase 보안 규칙은 항상 다음 선언으로 시작합니다.
service firebase.storage {
// ...
}
service firebase.storage
선언은 규칙 범위를 Cloud Storage로 지정하여 Cloud Storage 보안 규칙과 Cloud Firestore와 같은 다른 제품에 대한 규칙 간의 충돌을 방지합니다.
기본 읽기/쓰기 규칙
기본 규칙은 Cloud Storage 버킷을 식별하는 match
문, 파일 이름을 지정하는 match 문, 지정된 데이터를 읽을 때 허용되는 세부적인 allow
표현식으로 구성됩니다. allow
표현식은 관련된 액세스 방법 (예: 읽기, 쓰기)과 액세스가 허용되거나 거부되는 조건 을 지정합니다.
기본 규칙 세트에서 첫 번째 match
문은 {bucket}
와일드카드 표현식을 사용하여 규칙이 프로젝트의 모든 버킷에 적용됨을 나타냅니다. 다음 섹션에서 와일드카드 일치의 개념에 대해 더 논의할 것입니다.
service firebase.storage {
// The {bucket} wildcard indicates we match files in all Cloud Storage buckets
match /b/{bucket}/o {
// Match filename
match /filename {
allow read: if <condition>;
allow write: if <condition>;
}
}
}
모든 일치 문은 파일을 가리킵니다. match 문은 match /images/profilePhoto.png
에서와 같이 특정 파일을 가리킬 수 있습니다.
와일드카드 일치
규칙은 단일 파일을 가리키는 것 외에도 와일드카드 를 사용하여 match /images/{imageId}
에서와 같이 슬래시를 포함하여 이름에 지정된 문자열 접두사가 있는 모든 파일을 가리킬 수 있습니다.
위의 예에서 match 문은 {imageId}
와일드카드 구문을 사용합니다. 즉, /images/profilePhoto.png
또는 /images/croppedProfilePhoto.png
와 같이 이름 시작 부분에 /images/
가 있는 모든 파일에 규칙이 적용됩니다. match 문의 allow
식이 평가될 때 imageId
변수는 profilePhoto.png
또는 croppedProfilePhoto.png
와 같은 이미지 파일 이름으로 확인됩니다.
와일드카드 변수는 파일 이름 또는 경로 권한 부여를 제공하기 위해 match
내에서 참조될 수 있습니다.
// Another way to restrict the name of a file
match /images/{imageId} {
allow read: if imageId == "profilePhoto.png";
}
계층적 데이터
앞서 말했듯이 Cloud Storage 버킷에는 계층 구조가 없습니다. 그러나 파일 이름에 슬래시를 포함하는 파일 명명 규칙을 사용하면 중첩된 일련의 디렉터리 및 하위 디렉터리처럼 보이는 구조를 모방할 수 있습니다. Firebase 보안 규칙이 이러한 파일 이름과 상호 작용하는 방식을 이해하는 것이 중요합니다.
모두 /images/
스템으로 시작하는 이름을 가진 파일 세트의 상황을 고려하십시오. Firebase 보안 규칙은 일치하는 파일 이름에만 적용되므로 /images/
스템에 정의된 액세스 제어는 /mp3s/
스템에 적용되지 않습니다. 대신 다른 파일 이름 패턴과 일치하는 명시적 규칙을 작성하십시오.
service firebase.storage {
match /b/{bucket}/o {
match /images/{imageId} {
allow read, write: if <condition>;
}
// Explicitly define rules for the 'mp3s' pattern
match /mp3s/{mp3Id} {
allow read, write: if <condition>;
}
}
}
match
문을 중첩할 때 내부 match
문의 경로는 항상 외부 match
문의 경로에 추가됩니다. 따라서 다음 두 규칙 집합은 동일합니다.
service firebase.storage {
match /b/{bucket}/o {
match /images {
// Exact match for "images/profilePhoto.png"
match /profilePhoto.png {
allow write: if <condition>;
}
}
}
}
service firebase.storage {
match /b/{bucket}/o {
// Exact match for "images/profilePhoto.png"
match /images/profilePhoto.png {
allow write: if <condition>;
}
}
}
재귀 일치 와일드카드
파일 이름 끝에 일치하고 문자열을 반환하는 와일드카드 외에도 {path=**}
와 같이 와일드카드 이름에 =**
를 추가하여 더 복잡한 일치를 위해 다중 세그먼트 와일드카드 를 선언할 수 있습니다.
// Partial match for files that start with "images"
match /images {
// Exact match for "images/**"
// e.g. images/users/user:12345/profilePhoto.png is matched
// images/profilePhoto.png is also matched!
match /{allImages=**} {
// This rule matches one or more path segments (**)
// allImages is a path that contains all segments matched
allow read: if <other_condition>;
}
}
여러 규칙이 파일과 일치하는 경우 결과는 모든 규칙 평가 결과의 OR
입니다. 즉, 파일과 일치하는 규칙이 true
로 평가되면 결과는 true
입니다.
위의 규칙에서 "images/profilePhoto.png" 파일은 condition
또는 other_condition
중 하나가 true로 평가되면 읽을 수 있는 반면 "images/users/user:12345/profilePhoto.png" 파일은 other_condition
의 결과에만 종속됩니다. .
Cloud Storage 보안 규칙은 계단식으로 적용되지 않으며 요청 경로가 지정된 규칙이 있는 경로와 일치할 때만 규칙이 평가됩니다.
버전 1
Firebase 보안 규칙은 기본적으로 버전 1을 사용합니다. 버전 1에서 재귀 와일드카드는 0개 이상의 요소가 아닌 하나 이상의 파일 이름 요소와 일치합니다. 따라서 match /images/{filenamePrefixWildcard}/{imageFilename=**}
일치는 /images/profilePics/profile.png와 같은 파일 이름과 일치하지만 /images/badge.png는 일치하지 않습니다. 대신 /images/{imagePrefixorFilename=**}
을 사용하세요.
재귀 와일드카드는 일치 문의 끝에 와야 합니다.
더 강력한 기능을 사용하려면 버전 2를 사용하는 것이 좋습니다.
버전 2
Firebase 보안 규칙 버전 2에서 재귀 와일드 카드는 0개 이상의 경로 항목과 일치합니다. 따라서 /images/{filenamePrefixWildcard}/{imageFilename=**}
은 /images/profilePics/profile.png 및 /images/badge.png 파일 이름과 일치합니다.
rules_version = '2';
보안 규칙 상단:
rules_version = '2';
service cloud.storage {
match /b/{bucket}/o {
...
}
}
매치 문당 최대 하나의 재귀 와일드카드를 가질 수 있지만 버전 2에서는 이 와일드카드를 매치 문의 아무 곳에나 배치할 수 있습니다. 예를 들어:
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
// Matches any file in a songs "subdirectory" under the
// top level of your Cloud Storage bucket.
match /{prefixSegment=**}/songs/{mp3filenames} {
allow read, write: if <condition>;
}
}
}
세분화된 작업
일부 상황에서는 read
및 write
를 보다 세분화된 작업으로 나누는 것이 유용합니다. 예를 들어 앱에서 파일 삭제와 파일 생성에 대해 다른 조건을 적용하려고 할 수 있습니다.
read
작업은 get
및 list
로 나눌 수 있습니다.
write
규칙은 create
, update
및 delete
로 나눌 수 있습니다.
service firebase.storage { match /b/{bucket}/o { // A read rule can be divided into read and list rules match /images/{imageId} { // Applies to single file read requests allow get: if <condition>; // Applies to list and listAll requests (Rules Version 2) allow list: if <condition>; // A write rule can be divided into create, update, and delete rules match /images/{imageId} { // Applies to writes to file contents allow create: if <condition>; // Applies to updates to (pre-existing) file metadata allow update: if <condition>; // Applies to delete operations allow delete: if <condition>; } } } }
겹치는 일치 문
파일 이름이 둘 이상의 match
문과 일치할 수 있습니다. 여러 allow
식이 요청과 일치하는 경우 조건 중 하나 라도 true
액세스가 허용됩니다.
service firebase.storage {
match b/{bucket}/o {
// Matches any filename containing string '/images/'.
match /images/{imageId} {
allow read, write: if false;
}
// Matches all filenames containing string `/images/`
match /images/{imageId=**} {
allow read, write: if true;
}
}
}
위의 예에서 파일 이름에 /images/
문자열이 있는 파일에 대한 모든 읽기 및 쓰기는 첫 번째 규칙이 항상 false
임에도 불구하고 두 번째 규칙이 항상 true
이기 때문에 허용됩니다.
규칙은 필터가 아닙니다.
데이터를 보호하고 파일 작업을 수행하기 시작하면 보안 규칙은 필터가 아님을 명심하십시오. 파일 이름 패턴과 일치하는 파일 집합에 대해 작업을 수행할 수 없으며 Cloud Storage가 현재 클라이언트에 액세스 권한이 있는 파일에만 액세스할 것으로 예상합니다.
예를 들어 다음 보안 규칙을 사용합니다.
service firebase.storage {
match /b/{bucket}/o {
// Allow the client to read files with contentType 'image/png'
match /aFileNamePrefix/{aFileName} {
allow read: if resource.contentType == 'image/png';
}
}
}
거부됨 : 결과 집합에 contentType
이 image/png
가 아닌 파일이 포함될 수 있으므로 이 규칙은 다음 요청을 거부합니다.
편물
filesRef = storage.ref().child("aFilenamePrefix"); filesRef.listAll() .then(function(result) { console.log("Success: ", result.items); }) });
Cloud Storage 보안 규칙의 규칙은 잠재적인 결과에 대해 각 쿼리를 평가하고 클라이언트에게 읽기 권한이 없는 파일을 반환할 수 있는 경우 요청에 실패합니다. 액세스 요청은 규칙에서 설정한 제약 조건을 따라야 합니다.
다음 단계
Cloud Storage용 Firebase 보안 규칙에 대한 이해를 심화할 수 있습니다.
규칙 언어의 다음 주요 개념인 동적 조건 을 통해 규칙에서 사용자 권한 부여를 확인하고, 기존 데이터와 수신 데이터를 비교하고, 수신 데이터의 유효성을 검사하는 등의 작업을 수행할 수 있습니다.
일반적인 보안 사용 사례와 이를 해결하는 Firebase 보안 규칙 정의를 검토하세요.
Cloud Storage와 관련된 Firebase 보안 규칙 사용 사례를 탐색할 수 있습니다.