限制 Firestore Gmail 登录到特定域

Asi*_*taq 1 android firebase firebase-security google-cloud-firestore

我想限制用户使用特定的 gmail 域登录我的 Firestore 应用程序。我在这里发现了类似的问题但这与 Firestore 完全不同。所以让我解释一下我的要求我想要什么。

Suppose one company called abc.com are using the gmail services and they have integrated their all email accounts to gmail. So they can use gmail email services using that account. So I want to restrict to users that only use the username@abc.com gmail account to login to my firestore app.

I have searched a lot but didn't found any documentation about this.

jsa*_*ter 7

对此似乎没有可靠的 Firestore 解决方案,但我有一个复合解决方案:

  • 访问的第一个数据集合的安全规则,我在其中检查电子邮件域
  • 数据检索上的 catchError,我在其中检查错误代码“权限被拒绝”
  • 一个错误处理程序,它将调用身份验证服务并强制注销并重定向到未经授权的页面。

抱歉粘贴片段,但我无法让格式化程序格式化所有代码。

我的组件代码:

  ngOnInit(): void {
    this.leadsDataSubscription = this.leadService.getLeadsSnapshot()
      .pipe(
        catchError((e: any) => Observable.throw(this.errorHandler(e)))
      )
      .subscribe(data => {
        this.leadsDataSource.data = data;
        this.leadsDataSource.paginator = this.paginator;
        this.leadsDataSource.sort = this.sort;
      });
    this.currentUser = this.authSvc.getCurrentUser();
  }

  private errorHandler(error: any) {
    if (error.name === 'FirebaseError' && error.code === 'permission-denied') {
      this.leadsDataSubscription.unsubscribe()
      this.authSvc.logout('/unauthorized');
    }
  }
Run Code Online (Sandbox Code Playgroud)

我的服务代码

  logout(redirectURL?: string) {
    this.unsubscribe()
    this.afAuth.auth.signOut()
      .then(response => {
        this.snackBar.open('Signed out');
        this.router.navigate([redirectURL || '/']);
      })
      .catch(error => this.snackBar.open('Error signing out: ' + error));
  }
Run Code Online (Sandbox Code Playgroud)

Firestore 规则:

match /leads/{document=**} {
  allow read: if isAllowedDomain() && isSignedIn();
  allow update: if isAllowedDomain() && isSignedIn() && canUpdate()
  allow delete: if isAllowedDomain() && isSignedIn() && isCreator() && canWrite() || isGod()
  allow create: if isAllowedDomain() && isSignedIn() && userExists();
}
function isAllowedDomain() {
    return request.auth.token.email_verified == true &&
               request.auth.token.email.matches(".*@workdomain.se") ||
               request.auth.token.email.matches(".*@privatedomain.org")
}
Run Code Online (Sandbox Code Playgroud)