Android Firebase:第二个连接的数据库不允许在规则中进行身份验证

时间:2018-08-24 07:38:06

标签: java android firebase firebase-security firebase-security-rules

我已经从相同的Firebase项目连接了两个数据库,如下所示。

    //init the default db;
    FirebaseApp.initializeApp(this);

    //init the second db;
    FirebaseOptions.Builder builder = new FirebaseOptions.Builder();
    builder.setApplicationId("id"); //Same as default
    builder.setApiKey("key"); //Same as default 
    builder.setDatabaseUrl("https://second-db.firebaseio.com");

    try {
        FirebaseApp.initializeApp(this, builder.build(), "second-db");
    } catch (IllegalStateException e) {
        e.printStackTrace();
    }

获取参考。

public static DatabaseReference getSecondDbRef(String child) {
    FirebaseApp app = FirebaseApp.getInstance("second-db");
    return FirebaseDatabase.getInstance(app).getReference(child);
}

使用上面的方法,它可以工作,但是第二个数据库中的规则似乎未获得身份验证。如果可以的话。

 {
   "rules":{
          "users":{
                 "$uid":{
                       ".read":"auth.uid !== null",
                       // ".read":true // This works, so the issue is auth
                  }
          }
   }
}

即使用户经过身份验证,读取也会失败,默认数据库不存在此问题。初始化我缺少什么吗?

好吧,由于下面有突出显示,因此这是应用程序中的代码。

    private static final String  TEAMS_BD_ID   = "second-db"

    public void initFirebase() {
        FirebaseApp.initializeApp(this);

        FirebaseOptions.Builder builder = new FirebaseOptions.Builder();
        builder.setApplicationId("appId"); // //Same as default
        builder.setApiKey("key"); // //Same as default
        builder.setDatabaseUrl("https://teams-db.firebaseio.com");//Second Db

        try {
            FirebaseApp.initializeApp(this, builder.build(), TEAMS_BD_ID);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }
    }

    public static FirebaseApp getTeamsApp() {
        return FirebaseApp.getInstance(TEAMS_BD_ID);
    }

    public static String getTeamsUserUid() {
        return FirebaseAuth.getInstance(getTeamsApp()).getCurrentUser().getUid();
    }

    public static DatabaseReference getTeamsRef(String child) {
        return FirebaseDatabase.getInstance(getTeamsApp()).getReference(child);
    }

    public static DatabaseReference getTeamsRef() {
        return FirebaseDatabase.getInstance(getTeamsApp()).getReference();
    }

然后尝试阅读。

DatabaseReference r = getTeamsRef().child("users/" + getTeamsUserUid() + "/teams") 
// getTeamsUserUid()  This is null.

1 个答案:

答案 0 :(得分:1)

这只是一个猜测。

如果您使用FirebaseAuth#getInstance()获取身份验证实例,请使用第二个应用程序实例将其更改为FirebaseAuth#getInstance(FirebaseApp firebaseApp)