auth.token为空-Firebase实时数据库规则

时间:2020-09-29 21:16:35

标签: angular firebase firebase-realtime-database firebase-authentication firebase-security

我正在使用角度为9的google firebase实时数据库。每当我尝试执行写入操作时,都会被拒绝。我正在使用 firebase自定义声明进行验证。我认为firebase auth.token为null,因为我也无法访问用户电子邮件。 以下是我使用的规则:

{
  /* Visit https://firebase.google.com/docs/database/security to learn more about security rules. */
  "rules": {
    "notices": {
      ".read": "auth != null",
        "$noticeId": {
        ".write": "auth !=null && auth.token.author == true",
        ".validate": "newData.hasChildren(['title','author'])",
        "title": {
          ".validate": "newData.isString()"
          },
        "author": {
          ".validate": "newData.val() == auth.token.email"
          },
            "link": {
          ".validate": "newData.isString()"
          },
          "$other": { ".validate": false }

            }
        }
     }
}

已编辑:

我正在将Firebase函数与Admin-SDK一起使用来设置自定义声明。 我正在从Firebase函数调用setCustomClaim('author','abc @ example.org',true)。我确信自定义声明可以正常工作,因为我能够在前端获得价值。 设置自定义声明的功能:

const admin = require('firebase-admin');

async function getUserByEmail(email){
  return admin.auth().getUserByEmail(email).then((user) => generateResponse(200,null,user)).catch(() => generateResponse(417,`No user found for the provided email: ${email}`,false));
}

async function setCustomClaim(claimName, userEmail, setPrivilege = true) { 
    const userRes = await getUserByEmail(userEmail);
    if (!userRes.data) {
      return userRes;
    }
    let user = userRes.data;
    const currCustomClaims = (user.customClaims)?user.customClaims: {};
    currCustomClaims[claimName] = setPrivilege;
    try {
        await admin.auth().setCustomUserClaims(user.uid, currCustomClaims);
        return generateResponse(200, `User's ${claimName} property has been set to ${setPrivilege}`);
    } catch (e) {
      functions.logger.error(e)
      return generateResponse(500, `Some error occured! Please try again later.`);
    }
}

我创建了一个服务,负责将数据发送到Firebase实时数据库。

import { Injectable } from '@angular/core';

import { AngularFireDatabase, AngularFireObject } from '@angular/fire/database';

@Injectable({
  providedIn: 'root'
})
export class CmsService {

  private db: firebase.database.Reference;
  constructor(private angularFireDatabase: AngularFireDatabase) { 
    this.db = this.angularFireDatabase.database.ref('/notices');
  }

  createNotice( ){
    this.db.push({
      title: 'Hello Wolrd',
      link: 'https://aker99.com',
      author: 'abc@example.org'

    }, (err) => (!err) ? console.log('Successfully created') : console.log(err)
    );

  }

}

0 个答案:

没有答案