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
문, 파일 이름을 지정하는 일치 문, 지정된 데이터 읽기가 허용되는 시기를 자세히 설명하는 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
같이 특정 파일을 가리킬 수 있습니다.
와일드카드 일치
단일 파일을 가리키는 것 외에도 Rules는 와일드카드 를 사용하여 match /images/{imageId}
에서와 같이 슬래시를 포함하여 이름에 지정된 문자열 접두사가 있는 모든 파일을 가리킬 수 있습니다.
위의 예에서 일치 문은 {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 file names directly inside of '/images/'.
match /images/{imageId} {
allow read, write: if false;
}
// Matches file names anywhere under `/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';
}
}
}
Denied : 이 규칙은 결과 집합에 contentType
이 image/png
가 아닌 파일을 포함할 수 있기 때문에 다음 요청을 거부합니다.
편물
filesRef = storage.ref().child("aFilenamePrefix"); filesRef.listAll() .then(function(result) { console.log("Success: ", result.items); }) });
Cloud Storage 보안 규칙의 규칙은 잠재적인 결과에 대해 각 쿼리를 평가하고 클라이언트가 읽을 수 있는 권한이 없는 파일을 반환할 수 있는 경우 요청에 실패합니다. 액세스 요청은 규칙에 의해 설정된 제약 조건을 따라야 합니다.
다음 단계
Cloud Storage용 Firebase 보안 규칙에 대한 이해도를 높일 수 있습니다.
Rules 언어의 다음 주요 개념인 동적 조건 에 대해 알아보십시오. 이를 통해 Rules는 사용자 인증을 확인하고 기존 데이터와 들어오는 데이터를 비교하고 들어오는 데이터의 유효성을 검사할 수 있습니다.
일반적인 보안 사용 사례와 이를 해결하는 Firebase 보안 규칙 정의를 검토하세요.
Cloud Storage와 관련된 Firebase 보안 규칙 사용 사례를 살펴볼 수 있습니다.