【问题标题】:@firebase/testing - How to use auth custom claims in firestore rules tests?@firebase/testing - 如何在 Firestore 规则测试中使用身份验证自定义声明?
【发布时间】:2019-05-04 23:04:52
【问题描述】:

我对 Firestore 规则的所有测试都做得很好。但是,我仍然需要为管理员测试一些路径。

我的应用程序中的管理员不是 Firebase 管理员,它是一个在其 customClaims 中具有这样设置权限的用户:

claims: {admin: true}

如何使用 npm 包 @firebase/testing 模拟用户 customClaims?我想不通。

谢谢

PS:下面是我目前正在做的事情。

export default class TestApplication {

  public static getFirestoreInstance(auth, projectId: string): firebase.firestore.Firestore {
    return firebase
       .initializeTestApp({projectId, auth})
       .firestore();
  }
}


describe(){
    const defaultAuthUser = {uid: "alice", email: "alice@example.com", "token": {"admin": true};

    before(done => {
        currentProjectId = TestUtils.getRandomId();
        TestApplication.useFirestoreRules(currentProjectId, rules)
          .then(() => done())
          .catch(done);
    });

    it("I should be able to get another user if I'm an admin", () => {
      return firebase.assertSucceeds(
        TestApplication.getFirestoreInstance(defaultAuthUser, currentProjectId)
          .collection(FirebaseReference.USERS_REF)
          .doc(otherUserId)
          .get()
      );
    }).timeout(5000);
}

【问题讨论】:

  • 如果您展示一个 Firestore 规则测试示例,将会有所帮助。

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


【解决方案1】:

自定义声明可以作为 auth 对象中的顶级字段传递:

firebase.initializeTestApp({
  projectId: "my-test-project",
  auth: { uid: "alice", my_custom_claim: "foo" }
});

在问题的示例中,这一行:

const defaultAuthUser = {uid: "alice", email: "alice@example.com", "token": {"admin": true};

应改为:

const defaultAuthUser = {uid: "alice", email: "alice@example.com", admin: true};

【讨论】:

  • 遇到了同样的问题,结果@Chris 的解决方案解决了这个问题。我认为这应该被接受为正确答案。
【解决方案2】:

我认为上面的答案可能更具体一点。 初始化应用程序时,自定义声明需要在 auth 对象上。但在检查安全规则中的自定义声明时,自定义声明位于“令牌”属性 (request.auth.token.admin) 中。

初始化应用程序:

firebase.initializeTestApp({
  projectId: "my-test-project",
  auth: { uid: "alice", my_custom_claim: "foo", admin: true }
});

firebase.rules

...
match /posts/{postId} {
  allow update: if request.auth.token.admin 
}
...

【讨论】:

    【解决方案3】:

    我想您正在使用这种方法: https://firebase.google.com/docs/firestore/security/test-rules-emulator#run_local_tests

    所以在你的测试代码的某个地方你有:

      firebase.initializeTestApp({
       projectId: "my-test-project",
       auth: { uid: "alice", email: "alice@example.com" }
     });
    

    在此身份验证字段中,您可以将自定义声明模拟为:

    {
      "uid": "alice",
      "email": "alice@example.com",
      "token": {
        "admin" :true
      }
    }
    

    然后您可以在您的规则中使用 request.auth.token.admin。我在存储上试过这个,但同样/类似的也应该适用于 Firestore。

    【讨论】:

    • 谢谢,但我已经尝试过了。它似乎不起作用,我找不到任何关于它的文档。我也试过claimscustomClaims 而不是token
    • 我在存储上试过这个,它通过模拟器工作。我会在 Firestore 上尝试并让你知道。您是否尝试将 customClaims 字段放入令牌中?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-30
    • 2020-05-23
    • 2019-10-17
    • 2021-05-22
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    相关资源
    最近更新 更多