首页 > 解决方案 > Firebase Google signInWithRedirect 未在成功验证时重定向到指定页面

问题描述

以下问题需要一点帮助/解释。我正在为我的项目使用 Vue 和 Firebase。

我正在尝试通过调用signInWithRedirect来设置 Firebase Google 登录。身份验证本身有效,但不完全是我想要的。

在进行身份验证后,我需要它重定向到 /dashboard,但目前它在短暂加载后重定向回 /login 页面。

我知道我必须使用getRedirectResult,但我不确定如何准确调用它。如果有人能解释我如何正确编写代码以获得想要的结果,将不胜感激。

.signInWithRedirect(fb.googleProvider)
.then(credential => {
this.$store.commit("setCurrentUser", credential.user)
fb.usersCollection.doc(credential.user.uid).set({
}).then(() => {
this.$store.dispatch("fetchUserProfile")
this.updateGmailData()
this.$router.push("/dashboard")
}).catch(err => {
console.log(err)
})
}).catch(err => {
console.log(err);
});
},

我相信我的初始身份验证应该是这样的 -

googleLogin() {
fb.auth.signInWithPopup(fb.googleProvider)
}

之后我应该为getRedirectResult设置函数,它应该将路由器推送到 /dashboard?

如何进行重定向以等待 getRedirectResult 并在获得所需结果后重定向 /dashboard。

我不知道如何实施它。

标签: javascriptfirebasevue.jsfirebase-authenticationvue-router

解决方案


signInWithRedirect将重定向回将完成登录的同一页面。然后,您可以在用户登录后使用getRedirectResult()onAuthStateChanged侦听器重定向到您的仪表板。

在您的登录按钮单击处理程序中,调用:

// This will redirect to IdP for sign-in.
firebase.auth.signInWithRedirect(fb.googleProvider);

然后在同一页面上,您可以设置一个侦听器:

firebase.auth().onAuthStateChanged((user) => {
  if (user) {
    // User signed in, you can get redirect result here if needed.
    // ...
    this.$router.push("/dashboard");
    // ....
  } else {
    // Show sign in screen with button above.
  }
});

推荐阅读