简体   繁体   中英

How to add authentication persistence to Vue.js AWS-amplify app

I am attempting to build an AWS-Amplify authentication page for a Vue.js app. So far, I have been successful in implementing a login/logout module using the aws-amplify and aws-amplify-vue plugins. I have also implemented a route guard in router.js that prevents the unauthorized access. I am however, running into an issue where, after logging in, clicking the back arrow in the browser returns to the login menu even though I am still logged into the app. In previous apps that I've built using Firebase, I would normally add .onAuthStatechanged() method to the main.js (the entry point file) to handle authentication persistence, like so:

let app = ''

firebase.auth().onAuthStateChanged(() => {
  if (!app) {
    app = new Vue({
      router,
      store,
      render: h => h(App)
    }).$mount('#app')
  }
})

Is there a method similar to this in AWS Amplify or the aws-amplify-vue plugin? If not, are there any recommendations on how to implement auth persistence? Is there perhaps a way to configure the route guard to handle this? See my route guard below:

router.beforeResolve((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    let user;
    Vue.prototype.$Amplify.Auth.currentAuthenticatedUser().then(data => {
      if (data && data.signInUserSession) {
        user = data;
      }
      next()
    }).catch((e) => {
      next({
        path: '/'
      });
    });
  }
  next()
})

Based on the awsamplify documentation you can use a function called onAuthUIStateChanged which can be called upon creation to check the AuthState if it is "signedIn" then simply push the router to the home view. This would be the function in the Login.Vue view.

import { AuthState, onAuthUIStateChange } from '@aws-amplify/ui-components`;

export default {
  name: 'Login',
  created() {
    onAuthUIStateChange((nextAuthState, authData) => {
      if (nextAuthState === AuthStatus.SignedIn) {
          console.log('user successfully signed in!');
          this.$router.push('/profile');
        }
      if (!authData) { console.log('user is not signed in');
        }
     });
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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