如何在Vue中保持Cognito用户会话

时间:2020-01-23 17:24:43

标签: vue.js vuex amazon-cognito aws-amplify

在学习Vue的同时,我深入其中,并加入了一些泡菜...

我正在尝试使用 AWS Cognito 用户池来验证我的应用程序的会话。到目前为止,我已经设法创建了一个Userpool(在Cognito中),在Vue应用程序中创建了自定义登录/注销组件,并成功登录和注销。整个登录过程在浏览器的localStorage中创建了几个(大约10个)键/值对,这就是我在努力的地方。

我需要从 localStorage getItem 并将其存储在Vuex中,以便在执行 refresh 时能够从中检索令牌。状态,然后 setItem 回到本地存储。

这听起来非常容易,尽管我目前发现自己一次学习Vue,Vuex和AWS服务,这使我的恐慌程度增加了“眨眼”。

我当前的@click方法是这样的...

signIn: function() {
    Auth.signIn(this.formResponses.username, this.formResponses.password)
        .then(user => {
            console.log(user);
            this.$store.state.signedIn = !!user;
            this.$store.state.user = user;
            this.signedIn = true;
            this.$store.state.token = user.signInUserSession.idToken.jwtToken;
            // this.currentUserInfo();
        })
        .catch(err => console.log(err));
},

1 个答案:

答案 0 :(得分:0)

我建议您查看this walkthrough如何添加身份验证工作流,但是要点是,当用户尝试登录时,您会调度操作

async login(){
try{
await this.$store.dispatch('login', {formWithEmailAndPassword})
} catch(error){
console.log({error})
}

在您的商店中尝试使用Amplify的Auth服务调用“登录”(不要忘记使用import {Auth} from 'aws-amplify导入它们):

export const actions = {
    async login({commit}, {email, password}){
    const user = await Auth.signIn(email, password)
    commit('set', user)
    return user
    }
...

实际上是通过“设置”设置用户的:

export const mutations = {

    set(state,user){
    state.user = user
    }

...
相关问题