在用户登录后,为什么我必须用firebase对其进行身份验证?

时间:2020-01-11 13:54:18

标签: java firebase android-studio firebase-authentication google-signin

我已按照documentation在具有Firebase身份验证的android应用中实现了google登录。但是,我仍在尝试了解代码及其背后的逻辑。
因此,在用户成功使用自己的gmail帐户登录后,将调用 firebaseAuthWithGoogle 方法,并将帐户信息作为参数传递:

firebaseAuthWithGoogle(account); 

这是它的定义:

private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
        // We will put the data coming from the google account in MySQL database
        Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
    mFirebaseAuth.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 = mFirebaseAuth.getCurrentUser();

                    } else {
                        // If sign in fails, display a message to the user.
                        Log.w(TAG, "signInWithCredential:failure", task.getException());

                    }

                    // ...
                }
            });
}

}

我已经尝试根据documentation向自己解释:

用户成功登录后,

GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account); // Calling firebaseAuthWithGoogle
GoogleSignInAccount对象

获取一个 ID令牌 , 将其交换为 Firebase凭证

AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);

并通过Firebase进行身份验证

mFirebaseAuth.signInWithCredential(credential)

使用 Firebase凭据

对我来说, 100%清除的不是:
1.如果用户已经登录,为什么我必须通过Firebase进行身份验证?
2.如果用户已经登录,Firebase身份验证将扮演什么角色?
3.如果用户已经登录,则使用Firebase凭据登录意味着什么?

我知道这对某些人来说可能是微不足道的,但是对我来说,整个登录流程非常模糊,尤其是使用Firebase身份验证时。

1 个答案:

答案 0 :(得分:1)

使用Firebase进行身份验证时,您可以通过执行以下操作来访问当前登录的用户:

FirebaseUser user = mFirebaseAuth.getCurrentUser();

通过检索user,您还可以检索userId,可用于连接到Firebase数据库。

您还可以在再次打开应用程序时检查用户是否仍在登录:

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
    // User is signed in
} else {
    // No user is signed in
}

并在登录后将用户重定向到页面