为啥我必须在用户登录后使用 firebase 对用户进行身份验证?

Posted

技术标签:

【中文标题】为啥我必须在用户登录后使用 firebase 对用户进行身份验证?【英文标题】:Why do I have to authenticate the user with firebase after he has already signed-in?为什么我必须在用户登录后使用 firebase 对用户进行身份验证? 【发布时间】:2020-04-28 21:26:03 【问题描述】:

我已经按照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】:

当您使用 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

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

【讨论】:

谢谢。这就是使用 Firebase 身份验证的全部意义所在? Firebase 凭据登录是关于什么的?它与用户的初始登录不同吗?或者它是初始登录。这更令人困惑。

以上是关于为啥我必须在用户登录后使用 firebase 对用户进行身份验证?的主要内容,如果未能解决你的问题,请参考以下文章

Firebase身份验证登录必须允许单个设备登录

我可以让 Firebase 使用用户名登录过程吗?

使用firebase和flutter登录google后获取用户详细信息

Flutter firebase 登录用户在登录后返回 NULL currentUser

防止用户在注册firebase后自动登录[重复]

使用 Angular 和 Firebase 登录后获取用户配置文件