@ firebase / testing-如何在Firestore规则测试中使用auth自定义声明?

Spo*_*e44 5 testing firebase google-cloud-firestore firebase-security-rules

我对Firestore Rules的所有测试几乎都不错。但是,我仍然需要测试管理员的一些路径。

我的应用程序中的管理员不是Firebase管理员,而是具有在customClaims中设置如下权限的用户:

claims: {admin: true}

如何使用npm软件包模拟用户customClaims @firebase/testing?我不知道。

谢谢

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);
}
Run Code Online (Sandbox Code Playgroud)

小智 7

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

初始化应用程序:

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

firebase.rules

...
match /posts/{postId} {
  allow update: if request.auth.token.admin 
}
...
Run Code Online (Sandbox Code Playgroud)


Chr*_*ick 5

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

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

在问题的示例中,此行:

const defaultAuthUser = {uid: "alice", email: "alice@example.com", "token": {"admin": true};
Run Code Online (Sandbox Code Playgroud)

应更改为:

const defaultAuthUser = {uid: "alice", email: "alice@example.com", admin: true};
Run Code Online (Sandbox Code Playgroud)