将自定义 JWT 令牌传递给 firestore 以使用 flutter 进行身份验证

Passing custom JWT token to firestore for authentication using flutter

我想为我的 firestore 数据库创建一个规则,允许用户根据他们传递的自定义 JWT 令牌访问它。我的后端是在 .NET 中开发的,我正在使用 firebase 添加一些额外的 'live' 功能。

每个用户在登录时都会从 API 获得一个 JWT 令牌,我想知道如何将该令牌传递给 firestore 并创建一个允许用户拥有 read/write 的规则如果令牌有效则使用它访问

我正在努力解决的问题是能够将任何信息(body 除外)传递给 firestore。例如,在这段代码中,我会将 JWT 令牌作为 header 传递给 firebase 以及在 firebase 规则中我将如何访问此 header 并将其解码

正如您在下面看到的,我的数据库目前没有身份验证。

编码为post数据:

void sendMessage({
    String message,
    String clientId,
    String ptId,
    bool isPt,
  }) async {
    try {
      final messagesDoc = _db
          .collection('pt-info')
          .doc(ptId)
          .collection('clients')
          .doc(clientId)
          .collection('messages');

      await messagesDoc.add({
        'message': message,
        'dateTime': DateTime.now(),
        'sentByPt': isPt
      });
    } catch (e) {
      print(e);
    }
  }

Firestore 规则

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if true;
    }
  }
}

我要做什么(我不知道如何在此处解码 JWT 令牌或将其传递到此处,但这实际上是我正在尝试做的)

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if JWT.decode(CUSTOM_TOKEN).isValid()
    }
  }
}

Firestore 安全规则中唯一可用的信息是:

  1. 请求作用的路径。
  2. 更新的文档数据(用于写请求)。
  3. 发出请求的 Firebase 身份验证用户的身份验证令牌。

在这些选项之外,您无法将自定义信息传递给 Firestore 安全规则。如果你想传递额外的信息,它必须在这些地方之一。

最常见的是在现有令牌中以 custom token (minted with an Admin SDK), or custom claims 的形式传递 Firebase 身份验证令牌中的附加信息。在任何一种情况下,用户都必须使用 custom/customized 令牌登录 Firebase 身份验证,此时信息将在 request.auth.token.

下的安全规则中可用。