配置 Firestore 安全规则以允许用户仅访问自己的数据 - 有效

Mar*_*mes 7 typescript firebase-security google-cloud-firestore

将 firestore 与 angularfire2 rc 2 一起使用。

在没有有效安全规则的情况下,一切都在开发中运行良好。

这些是无安全规则 - 客户端代码将在$COLLECTION_NAME/document没有问题的情况下创建、更新和删除集合。

service cloud.firestore {
    match /databases/{database}/documents {
        match /collectionA/{userId=**} { 
            allow read, write: if true;
        }
        match /collectionB/{userId=**}  {
            allow read, write: if true;
        }
        match /collectionC/{userId=**}  {
            allow read, write: if true;
        }
        match /collectionD/{userId=**}  {
            allow read, write: if true;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我想达到的目的是只允许用户访问他们自己的数据。

我从以下规则开始:

service cloud.firestore {
    match /databases/{database}/documents {
        match /collectionA/{userId=**} { 
            allow read, write: if request.auth.uid == userId;
        }
        match /collectionB/{userId=**}  {
            allow read, write: if request.auth.uid == userId;
        }
        match /collectionC/{userId=**}  {
            allow read, write: if request.auth.uid == userId;
        }
        match /collectionD/{userId=**}  {
            allow read, write: if request.auth.uid == userId;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,只要我添加了任何类型的限制性规则,包括仅验证请求就被授权。

match /databases/{database}/documents {
    match /collectionA/{userId=**} { 
       allow read, write: if request.auth;
    }
    match /collectionB/{userId=**}  {
        allow read, write: if request.auth;
    }
    match /collectionC/{userId=**}  {
        allow read, write: if request.auth;
    }
    match /collectionD/{userId=**}  {
         allow read, write: if request.auth;
    }
}
Run Code Online (Sandbox Code Playgroud)

我收到代码权限错误。

[code=permission-denied]:权限缺失或不足。

FirebaseError:权限缺失或不足。

每个 {userId} 文档都包含一个集合,该集合又包含文档,因此完整路径可能类似于

const entryCollection: AngularFirestoreCollection<Entry> = this.angularfirestore.collection('collectionC/' + user.uid + '/records' + '/2017-40' + '/entries');
Run Code Online (Sandbox Code Playgroud)

应该对请求进行身份验证,因为仅在使用 firebase 身份验证进行身份验证后才在客户端中授予访问权限。日志记录表明 uid 存在,实际上在 collectionA 或 B 或 C 或 D 下创建文档时, user.uid 文档使用 uid 命名。

Mik*_*ald 8

简短的回答是{userId=**}结果userId是 apath而不是 a string。这意味着将它与request.auth.uid(这是一个字符串)进行比较将失败。相反,您可能需要以下内容:

service cloud.firestore {
    match /databases/{database}/documents {
        match /collectionA/{userId}/{allSubcollections=**} { 
            allow read, write: if request.auth.uid == userId;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这将保证userId是一个字符串,然后匹配适当的子集合(再次注意,allSubcollections将是 a path)。