Firebase 实时数据库 + Google 登录



当我只想使用 Google 登录时,如何使用 Firebase 实时数据库?有没有办法告诉数据库我已登录?

默认情况下,规则说:

write: auth != null 
read: auth != null

如何告诉数据库,在我通过谷歌登录后,"auth != null".

我希望我说清楚了,如果没有,请告诉我。

编辑:我将规则更改为以下内容,但仍然没有任何内容

{
  "rules": {
    ".read": "auth != null && auth.provider == 'google'",
    ".write": "auth != null && auth.provider == 'google'"
  }
}

所以看起来我已经准备好了,因为在规则模拟器中它可以工作,但我仍然不知道如何在我在 Android 手机中登录我的 Google 帐户后告诉数据库。

登录后,我做了一个简单的写作:

DatabaseReference mDatabaseReference = FirebaseDatabase.getInstance().getReference("message");
mDatabaseReference.setValue("HELLO");

使用 Google 登录会生成有效的帐号和凭据。 然后,您需要使用该信息向 Firebase 进行身份验证。 本文档中概述了这些步骤。

以下是文档中使用 Google 登录凭据创建经过身份验证的 Firebase 用户的示例代码:

private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
    Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        // Sign in success, update UI with the signed-in user's information
                        Log.d(TAG, "signInWithCredential:success");
                        FirebaseUser user = mAuth.getCurrentUser();
                        updateUI(user);
                    } else {
                        // If sign in fails, display a message to the user.
                        Log.w(TAG, "signInWithCredential:failure", task.getException());
                        Toast.makeText(GoogleSignInActivity.this, "Authentication failed.",
                                Toast.LENGTH_SHORT).show();
                        updateUI(null);
                    }
                    // ...
                }
            });
}

然后,您可以设置数据库安全规则以限制对授权用户的访问:

{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}

最新更新