Firebase 安全规则权限不足

时间:2021-07-02 18:03:10

标签: angular firebase google-cloud-firestore firebase-security

我在我的 firebase 项目中拥有所有者角色,我正在尝试保护我的 Firestore 数据库。我希望我的收藏在默认情况下受到保护,并且只有在我为其制定规则时才能访问。我在生产模式下创建了我的数据库。但是,出于某种原因,即使我指定了允许我访问集合的规则,我也会收到 Missing or insufficient permissions 错误

例如,当我注册用户时,我还想创建自己的用户集合。 注册用户有效,但创建我的收藏无效。

注册用户查询(有效并将用户添加到 firebase 身份验证)

register(value) : Promise<any> {
    return new Promise<any>((resolve, reject) => {
        this.afAuth.createUserWithEmailAndPassword(value.email, value.password)
        .then(res => {
            resolve(res);
        }, err => {
            console.log(err)
            reject(err);
            })
    
    });
}

创建用户集合查询(CreateCurrentUserCollection 不起作用)

public async getCurrentUser() : Promise<any> 
    {
        return new Promise<any>((resolve, reject) => {
            let user = this.afAuth.onAuthStateChanged(function(user){
                if (user) {
                    resolve(user);
                } else {
                    reject('No user logged in');
                }
            });
        });
    }   

public CreateCurrentUserCollection(): void
{
  this.authService.getCurrentUser().then(res => {
        this.firestore.collection<User>("usersBackup")
            .add({
                uid: res.uid,
                username: res.email
            })
  });
}

Firebase 规则

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
      
       match /users {
        allow read, write: if
          request.time < timestamp.date(2221, 7, 20);
       }
       
       match /usersBackup {
        allow read, write: if
          request.time < timestamp.date(2221, 7, 20);
       }
  }
}

如果我添加以下规则,例如

match /{document=**} {
  allow read, write: if request.auth != null;

确实有效。但是,我的其他安全规则都不起作用,我想阻止某些用户访问某些文档。我错过了什么或做错了什么?如果您需要更多信息,请提前告诉我,谢谢。

更新

正如 Dharmaraj 在他的回答中所指出的,安全规则必须指向文档而不是集合。这解决了我的收藏之一的问题。但是,我也有一个项目集合,其中包含一个名为 projectMembers 的数组字段。我只希望在 projectMembers 数组中有 uid 的用户可以访问项目文档。出于某种原因,它总是给我 Missing or insufficient permissions 错误,即使项目集合为空。

查询

    public getProjectsOfUser(userUid: string) : Observable<IProject[]> {
        return this.firestore.collection<IProject>("projects", ref => 
            ref.where("projectMembers", "array-contains", userUid))
           .valueChanges({ idField: 'id'});
}

Firebase 规则

    rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
      
       match /users/{userID} {
        allow read, write: if isSignedIn() && request.auth.uid == userID
       }
       
       match /usersBackup/{document=**} {
        allow read, write: if
          request.time < timestamp.date(2221, 7, 20);
       }
        
      match /projects/{projectId} {
        allow read, write: if 
            isProjectMember(projectId, request.auth.uid);
      }
      
      //functions
    function isSignedIn()
    {
        return request.auth != null;
    }
    
    function isProjectMember(projectId, userId) {
    return userId in get(/databases/$(database)/documents/projects/$(projectId)).data.projectMembers;
    }
    
  }
}

数据库结构 enter image description here

Firebase Playground enter image description here

JWT 令牌通过 Angular 发送到 Firebase enter image description here

1 个答案:

答案 0 :(得分:2)

documentation中所述,

<块引用>

所有匹配语句都应该指向文档,而不是集合。 match 语句可以指向特定文档,如 match /cities/SF 或使用通配符指向指定路径中的任何文档,如 match /cities/{city}。

如果您只希望用户编辑他们自己的文档,您应该尝试:

match /users/{userID} {
  allow read, write: request.auth != null && request.auth.uid == userID;
}

如果没有,那么您可以尝试添加一个 recursive wildcard,以便该规则将应用于该集合中的所有文档:

match /users/{document=**} {
  allow read, write: request.time < timestamp.date(2221, 7, 20);
}

请注意,如果您使用递归通配符,任何人都可以写入任何文档。

更新: 检查数组中是否存在 UID。

allow read, write: if request.auth != null && request.auth.uid in resource.data.projectMembers