【问题标题】:How to add authentication persistence to Vue.js AWS-amplify app如何向 Vue.js AWS-amplify 应用程序添加身份验证持久性
【发布时间】:2019-11-19 20:38:00
【问题描述】:

我正在尝试为 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()
})

【问题讨论】:

  • 您指定user = data,但不使用user。之前看过这段代码,但是还是不明白为什么会这样。

标签: javascript amazon-web-services vue.js vue-router aws-amplify


【解决方案1】:

根据awsamplify 文档,您可以使用一个名为 onAuthUIStateChanged 的​​函数,该函数可以在创建时调用以检查 AuthState 是否为“已签名”,然后只需将路由器推送到主视图。这将是 Login.Vue 视图中的函数。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-25
    • 1970-01-01
    • 2020-04-01
    • 2021-03-17
    • 1970-01-01
    • 1970-01-01
    • 2020-09-08
    相关资源
    最近更新 更多