Redirect to requested page after login using vue-router

前端 未结 8 1949
臣服心动
臣服心动 2020-12-07 20:40

In my application some routes are just accessible for authenticated users.
When a unauthenticated user clicks on a link, for which he has to be signed in, he will be redi

8条回答
  •  北荒
    北荒 (楼主)
    2020-12-07 21:04

    Following on from Matt C's answer, this is probably the simplest solution but there were a few issues with that post, so I thought it best to write a complete solution.

    The destination route can be stored in the browser's session storage and retrieved after authentication. The benefit of using session storage over using local storage in this case is that the data doesn't linger after a broswer session is ended.

    In the router's beforeEach hook set the destination path in session storage so that it can be retrieved after authentication. This works also if you are redirected via a third party auth provider (Google, Facebook etc).

    router.js

    // If user is not authenticated, before redirecting to login in beforeEach

    sessionStorage.setItem('redirectPath', to.path)
    

    So a fuller example might look something like this. I'm using Firebase here but if you're not you can modify it for your purposes:

    router.beforeEach((to, from, next) => {
      const requiresAuth = to.matched.some(x => x.meta.requiresAuth);
      const currentUser = firebase.auth().currentUser;
    
      if (requiresAuth && !currentUser) {
        sessionStorage.setItem('redirectPath', to.path);
        next('/login');
      } else if (requiresAuth && currentUser) {
        next();
      } else {
        next();
      }
    });
    

    login.vue

    In your login method, after authetication you will have a line of code that will send the user to a different route. This line will now read the value from session storage. Afterwards we will delete the item from session storage so that it is not accidently used in future (if you the user went directly to the login page on next auth for instance).

    this.$router.push(sessionStorage.getItem('redirectPath') || '/defaultpath');
    sessionStorage.removeItem('redirectPath');
    

    A fuller example might look like this:

    export default Vue.extend({
      name: 'Login',
      data() {
        return {
          loginForm: {
            email: '',
            password: ''
          }
        }
      },
      methods: {
        login() {
          auth.signInWithEmailAndPassword(this.loginForm.email, this.loginForm.password).then(user => {
    
            //Go to '/defaultpath' if no redirectPath value is set
            this.$router.push(sessionStorage.getItem('redirectPath') || '/defaultpath');
    
            //Cleanup redirectPath
            sessionStorage.removeItem('redirectPath');
    
          }).catch(err => {
            console.log(err);
          });
        },
      },
    });
    

提交回复
热议问题