[英]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.我正在尝试为 Vue.js 应用程序构建 AWS-Amplify 身份验证页面。 So far, I have been successful in implementing a login/logout module using the
aws-amplify
and aws-amplify-vue
plugins.到目前为止,我已经成功地使用
aws-amplify
和aws-amplify-vue
插件实现了登录/注销模块。 I have also implemented a route guard in router.js that prevents the unauthorized access.我还在 router.js 中实现了一个路由保护,以防止未经授权的访问。 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:在我之前使用 Firebase 构建的应用程序中,我通常会在 main.js(入口点文件)中添加
.onAuthStatechanged()
方法来处理身份验证持久性,如下所示:
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? AWS Amplify 或
aws-amplify-vue
插件中是否有类似的方法? 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.根据awsamplify文档,您可以使用名为 onAuthUIStateChanged 的 function 可以在创建时调用它来检查 AuthState 是否为“已签名”,然后只需将路由器推送到主视图。 This would be the function in the Login.Vue view.
这将是 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.