如何在用户使用Firebase身份验证登录后进行重定向?

8

用户登录后如何重定向到另一个网页?

目前,当用户登录时,数据被检索出来,但它没有将用户重定向到另一个网站。

我知道应该使用“getRedirectResult”,但有人能向我展示如何使用它以及如何重定向用户到不同的网页,并保留检索到的用户数据吗?

我的javascript代码:

function toggleSignIn() {
  if (!firebase.auth().currentUser) {
    // [START createprovider]
    var provider = new firebase.auth.GoogleAuthProvider();
    // [END createprovider]
    // [START addscopes]
    provider.addScope('https://www.googleapis.com/auth/plus.login');
    // [END addscopes]
    // [START signin]
    firebase.auth().signInWithPopup(provider).then(function(result) {
      // This gives you a Google Access Token. You can use it to access the Google API.
      var token = result.credential.accessToken;
      // The signed-in user info.
      var user = result.user;
      // [START_EXCLUDE]
      document.getElementById('quickstart-oauthtoken').textContent = token;
      // [END_EXCLUDE]
    }).catch(function(error) {
      // Handle Errors here.
      var errorCode = error.code;
      var errorMessage = error.message;
      // The email of the user's account used.
      var email = error.email;
      // The firebase.auth.AuthCredential type that was used.
      var credential = error.credential; 
      // [START_EXCLUDE]
      if (errorCode === 'auth/account-exists-with-different-credential') {
        alert("You have already signed up with a different auth provider for that email.");
        // If you are using multiple auth providers on your app you should handle linking
        // the user's accounts here.
      }
  else if (errorCode === 'auth/auth-domain-config-required') {
    alert("An auth domain configuration is required"); 
      }
      else if (errorCode === 'auth/cancelled-popup-request') {
          alert("Popup Google sign in was canceled");
      }
      else if (errorCode === 'auth/operation-not-allowed') {
          alert("Operation is not allowed");
      }
      else if (errorCode === 'auth/operation-not-supported-in-this-environment') {
          alert("Operation is not supported in this environment");
      }
      else if (errorCode === 'auth/popup-blocked') {
          alert("Sign in popup got blocked");
      }
      else if (errorCode === 'auth/popup-closed-by-user') {
          alert("Google sign in popup got cancelled");
      }
      else if (errorCode === 'auth/unauthorized-domain') {
          alert("Unauthorized domain");
      }
       else {
        console.error(error);
      }
      // [END_EXCLUDE]
    });
    // [END signin]
  } else {
    // [START signout]
    firebase.auth().signOut();
    // [END signout]
  }
  // [START_EXCLUDE]
  document.getElementById('quickstart-sign-ing').disabled = false;
  // [END_EXCLUDE]
}
4个回答

17
从用户获取电子邮件和密码,然后将这些值传递给 signInWithEmailAndPassword ,如果出现错误,它将打印消息,否则 Firebase 将成功签入用户。
firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
    // Handle Errors here.
    var errorCode = error.code;
    console.log(error.Message);

});

您还需要一个监听器来处理登录和注销状态。这是您可以将用户重定向到登录成功的页面。

要处理登录和注销,请始终使用 onAuthStateChanged()

//Handle Account Status
firebase.auth().onAuthStateChanged(user => {
  if(user) {
    window.location = 'home.html'; //After successful login, user will be redirected to home.html
  }
});

当有人登录时,user 将被填充上用户详细信息,您可以使用它来重定向到另一页。


1
这对我来说似乎不是很安全,有人可以检查那段代码并手动输入home.html。是否有更安全的方法来重定向用户? - André Kuhlmann
3
我认为你会假设,尽管他们可以访问该页面,但由于该用户未经授权,因此不会填充任何数据(包括敏感信息和其他信息)。 - Aarmora
我们如何在登录后的重定向页面上提供注销功能?我想在第二个页面上使用firebase.auth().signOut。我该怎么做? - Rahul Mishra
2
这会创建一个无限重定向窗口到home.html的循环... - Taylor A. Leach
@TaylorA.Leach 我现在也面临同样的问题,没有解决方案,把它放在认证监听器中会创建一个无限循环。 - kamp
显示剩余2条评论

6
你只需要在initApp()中添加两个重定向即可实现此操作。我提到的是quickstart git仓库 https://github.com/firebase/quickstart-js/blob/master/auth/email.html,因为我是通过重复的问题 Redirecting to a page after Firebase login - Javascript来到这里的。

1) 在第163行,添加您想要已登录用户重定向到的页面:

162 //User is signed in.
163 window.location = ‘loggedIn.html’;
164 var displayName = user.displayName;

2) 在第180行(现在是181行,因为上面添加了一行),添加一个重定向回登录页面:

180 // User is signed out.
181 window.location = ‘index.html’;
182 // [START_EXLUDE]

您需要将整个脚本添加到主页和登录后的页面中,即包括原始git库中第37至201行之间的所有内容(包括脚本标签),但要添加上述两个重定向内容。
如果您尝试直接访问loggedIn.html而未登录,则initApp函数将检查您是否已登录,发现您未登录,然后将您重定向到登录页面。唯一的问题是在重定向之前会出现快速闪烁的已登录内容,为了解决这个问题,您可以将此页面的正文设置为隐藏,并且如果用户已登录,则运行一个删除隐藏类的脚本。
最后,您需要在原始仓库的第46行的toggleSignIn函数中添加一个重定向。
45  firebase.auth().signOut();
46  window.location = ‘index.html’;
47  // [END signout]

1
假设我想要在保留授权令牌的同时切换到另一页,并且稍后还需要当前用户的详细信息,我该怎么做呢? - Barungi Stephen

4
如果你在构建单页应用程序,那么你很可能不需要进行重定向。相反,当用户登录时,您只需更改应用程序状态即可。但是,如果您确实想要更改URL,则可以在成功回调中使用JavaScript设置窗口位置。例如:
window.location = '/logged_in.html'

注意,在新页面上,您还需要监听授权状态:
firebase.auth().onAuthStateChanged(function(currentUser) {
  if (currentUser) {
    // the user is logged in, you can bootstrap functionality now
  }
});

通常情况下,Firebase网络应用程序将更好地工作,如果您将您的应用程序构建成需要在状态转换之间进行硬页面加载。所有内容都可以并且理想情况下应该使用JavaScript进行管理,而不需要额外的页面加载。


你知道如何在我的JavaScript代码中实现这个吗? - Matrix
重定向是有效的,但它无法保留检索到的用户数据。 - Matrix
嗨,Mulu,你是否试图在登录页面上使用不同的来源进行登录?Firebase web身份验证仅限单个主机来源。如果您在登录后重定向到不同的网页,则无法使用已登录用户。 - bojeil
1
然而,有没有一种方法可以保持已登录的用户。我听说通过使用“getRedirectResult”,您可以保持已登录的用户。 - Matrix

3

您可以在JavaScript中赋值给location, 例如: location = 'https://google.com' 或者 location = '/logged-in-page.html'


你是在说实际按钮被调用的javascript还是其他地方?(抱歉,我对这个还有点新) - Tal Amos
添加到登录后加载的任何页面中。 - csander

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接