【问题标题】:How to persist cognito user session in Vue如何在 Vue 中持久化 cognito 用户会话
【发布时间】:2020-05-10 01:15:43
【问题描述】:

在学习 Vue 的过程中,我进入了最深层次,并陷入了一些困境......

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

我需要从 localStorage getItem 并将其存储在 Vuex 中,以便当我执行 refresh 时,我可以从中检索令牌state 和 setItem 返回到 localStorage。

这一切听起来都非常简单,尽管我现在发现自己同时学习 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));
},

【问题讨论】:

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


    【解决方案1】:

    我建议您查看 this walkthrough 以了解如何添加身份验证工作流,但要点是当用户尝试登录时,您会发送一个操作

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

    在您的商店中调用“登录”并尝试使用 Amplify 的身份验证服务(不要忘记使用 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
        }
    ...
    

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

    export const mutations = {
    
        set(state,user){
        state.user = user
        }
    
    ...
    

    【讨论】:

    • 使用 cognito 和 amplify 有什么区别?
    猜你喜欢
    • 2019-07-31
    • 2019-02-08
    • 2015-11-30
    • 1970-01-01
    • 2021-12-26
    • 2019-04-28
    • 2020-06-14
    • 1970-01-01
    • 2013-02-21
    相关资源
    最近更新 更多