简体   繁体   English

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

[英]How to redirect after a user signs in with Firebase authentication?

How can I redirect to a different webpage after the user has signed in? 用户登录后如何重定向到其他网页?

Currently when a user logs in, data gets retrieved however, it doesn't redirect the user to a different website. 目前,当用户登录时,会检索数据,但不会将用户重定向到其他网站。

I know I should use 'getRedirectResult', but can someone show me how to use it and how it redirect the user to a different webpage, maintaining the retrieved user data. 我知道我应该使用'getRedirectResult',但有人可以告诉我如何使用它以及如何将用户重定向到不同的网页,维护检索到的用户数据。

My javascript work: 我的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]
}

If you're building a single-page style application, you likely don't need to redirect. 如果您正在构建单页样式应用程序,则可能不需要重定向。 Instead you would just change your application state when the user logs in. If you do want to change the URL, however, you can simply set the window location using JavaScript in your success callback. 相反,您只需在用户登录时更改应用程序状态。但是,如果您确实要更改URL,则可以在成功回调中使用JavaScript设置窗口位置。 For example: 例如:

window.location = '/logged_in.html'

Note that on the new page you will need to listen for the auth state as well: 请注意,在新页面上,您还需要监听身份验证状态:

firebase.auth().onAuthStateChanged(function(currentUser) {
  if (currentUser) {
    // the user is logged in, you can bootstrap functionality now
  }
});

In general Firebase applications on the web will work better if you don't structure your app to need hard page loads in between state transitions. 一般而言,如果您构建应用程序以在状态转换之间需要硬页面加载,则Web上的Firebase应用程序将更好地工作。 Everything can and ideally should be managed using JavaScript without requiring an extra page load. 一切都可以并且理想情况下应该使用JavaScript进行管理,而无需额外的页面加载。

You just need to add two redirects inside initApp() to make this happen. 您只需要在initApp()中添加两个重定向即可实现。 I'm referring to the quickstart git repo https://github.com/firebase/quickstart-js/blob/master/auth/email.html , as I came here via the duplicate question Redirecting to a page after Firebase login - Javascript 我指的是快速启动git repo https://github.com/firebase/quickstart-js/blob/master/auth/email.html ,因为我是通过重复的问题来到这里Firebase登录后重定向到一个页面 - Javascript

1) on line 163, add the page you want logged-in users to be redirected to: 1)在第163行,添加要将登录用户重定向到的页面:

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

2) on line 180 (now 181 because of the add above), add a redirect back to the login page: 2)在第180行(由于上面的添加,现在为181),将重定向添加回登录页面:

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

You need to add the entire script to both the index and the logged in pages - so everything (including the script tags) between lines 37 and 201 from the original git repo (but with the two redirect additions above). 您需要将整个脚本添加到索引和登录页面 - 所以所有(包括脚本标记)在第37行和第201行之间来自原始git仓库(但上面有两个重定向添加)。

Now, if you try to go directly to loggedIn.html without logging in, the initApp function will check if you are logged in, see that you aren't, and redirect you to the login page. 现在,如果您尝试在不登录的情况下直接转到loggedIn.html,initApp函数将检查您是否已登录,看看您是否已登录,并将您重定向到登录页面。

The only issue is you get a quick flash of the logged content before the redirect, so to get around this you could set the body of this page to be hidden, and have a script that runs if the user is logged in that removes the hidden class. 唯一的问题是您在重定向之前快速刷新记录的内容,因此为了解决这个问题,您可以将此页面的主体设置为隐藏,并且如果用户已登录则运行脚本以删除隐藏的内容类。

Lastly, you'll want to add a redirect inside the toggleSignIn function, on line 46 of the original repo: 最后,您需要在原始仓库的第46行的toggleSignIn函数中添加重定向:

45  firebase.auth().signOut();
46  window.location = ‘index.html’;
47  // [END signout]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM