首页 > 解决方案 > 我们如何将标头值设置为 Cloud Firestore 中的身份验证

问题描述

我已经在firebase中应用了这个规则。在firestore auth中添加了一个用户并相应地更改了规则。我的自定义firestore规则是

match /{document=**} {
        allow read, write :if request.auth == 'Here user values will add';

从我的nestjs代码中,用户已添加为控制器类中的标头,并将此值传递到服务层,但是当在我们的firebase服务类中传递此值时,这是我在firebase服务类中的以下代码。

下面是我的控制器类

@Get('/list')
async getDocumentList(@Headers('user') user: string): Promise<any> {

 console.log("controller"+user);
    try {
        return await this.incidentService.getIncidentList(user);

    } catch (e) {
        throw new HttpException(e.message, HttpStatus.BAD_REQUEST);
    }
}

和firestore服务类是: -

async getDocumentList(collectionName: string,user ): Promise<any> {

    console.log(user);
    
    const docSnapshot = await firestore().collection(collectionName).get();                    
                          
    const docList = [];

    docSnapshot.forEach(doc => {
        docList.push(doc.data());
    });
    return docList;
}

我想知道如何将用户值传递/通知或设置条件到firestore,以便将此用户值作为管理员并基于此值应用规则?

我们的 Firestore 服务类中的代码是什么?

标签: typescriptgoogle-cloud-firestorefirebase-security

解决方案


从您的读取请求传递到 Firestore 安全规则的唯一信息是:

  • 正在请求的路径(和或查询)。
  • 来自客户端的当前身份验证对象,包括其 ID 令牌中的任何信息。

您不能传递其他信息并期望它显示在安全规则中。

因此,如果您想将特定用户标记为应用程序管理员并基于此在您的安全规则中授予他们特定的访问权限,您必须将该信息嵌入到上述项目之一中。

典型的方法是将此信息作为自定义声明添加到 ID 令牌中,或者将其存储在数据库本身中并根据 UID 进行查找


推荐阅读