簡體   English   中英

如何將身份驗證持久性添加到 Vue.js AWS-amplify 應用程序

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

我正在嘗試為 Vue.js 應用程序構建 AWS-Amplify 身份驗證頁面。 到目前為止,我已經成功地使用aws-amplifyaws-amplify-vue插件實現了登錄/注銷模塊。 我還在 router.js 中實現了一個路由保護,以防止未經授權的訪問。 但是,我遇到了一個問題,登錄后,即使我仍然登錄到應用程序,單擊瀏覽器中的后退箭頭也會返回登錄菜單。 在我之前使用 Firebase 構建的應用程序中,我通常會在 main.js(入口點文件)中添加.onAuthStatechanged()方法來處理身份驗證持久性,如下所示:

let app = ''

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

AWS Amplify 或aws-amplify-vue插件中是否有類似的方法? 如果沒有,是否有關於如何實現身份驗證持久性的建議? 有沒有辦法配置路由保護來處理這個問題? 請參閱下面的路線守衛:

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()
})

根據awsamplify文檔,您可以使用名為 onAuthUIStateChanged 的 function 可以在創建時調用它來檢查 AuthState 是否為“已簽名”,然后只需將路由器推送到主視圖。 這將是 Login.Vue 視圖中的 function。

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');
        }
     });
   }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM