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

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

我已经按照 documentation 在我的 Android 应用程序中使用 Firebase 身份验证实现了 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 token , 将其兑换为 Firebase 凭证

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

并使用 Firebase 进行身份验证

mFirebaseAuth.signInWithCredential(credential)

使用 Firebase 凭据

我不100%清楚的是:
1. 如果用户已经登录,为什么我必须通过 Firebase 进行身份验证?
2. 如果用户已登录,Firebase 身份验证将发挥什么作用?
3. 如果用户已经登录,使用 Firebase 凭据登录意味着什么?

我知道这对某些人来说可能听起来微不足道,但对我来说,整个登录流程相当模糊,尤其是 Firebase 身份验证。

最佳答案

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

FirebaseUser user = mFirebaseAuth.getCurrentUser();

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

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

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

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

关于java - 为什么我必须在用户登录后使用 firebase 对其进行身份验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59695050/

相关文章:

firebase - 如果我只使用 flutter web(没有 android 或 ios 应用程序),我是否还应该在 index.html 和 main.dart 中初始化 firebase 应用程序两次?

android - 动态创建自定义 ListView 问题

android - 调试 'app' 可以,但在 android studio 中无法运行 'app'

android - Gradle + Annotations + Flavors = 不会运行注释处理器

java - ant 问题中的旧版 IzPack

java - apache poi - 多次循环同一数组

java - 不显示对象标签,仅显示其 JAXB 属性

java - Android:另一个线程导致 UI 无响应?

android - Amazon Pinpoint 和 Ionic - 应用程序处于后台时推送通知不起作用

ios - 应用程序的实现 :openURL:sourceApplication:annotation: not found in (Xcode 8. 1)