注销时的vuex空状态

时间:2018-03-29 05:24:13

标签: javascript security vue.js vuex

我的问题的快速故事:

  1. 页面加载
  2. 时,我的vuex状态中绝对没有数据存储
  3. 如果用户已登录(或者信息存储在window.localStorage中并因此自动登录),我的vuex商店会从需要身份验证的套接字中检索所有信息。
  4. 然后用户退出,但我的vuex状态保存仍保留其所有数据
  5. 这将是一个安全问题,因为未登录公用电脑上的人(或黑客)可以查看用户退出前的状态。

    我看过How to clear state in vuex store? 但我觉得这是一个黑客,应该避免。

    我目前的解决方案是使用location.reload();

    刷新页面
      

    有没有更好的方法来防止此数据泄漏?

4 个答案:

答案 0 :(得分:2)

存储在Vue中的所有对象都是可观察的。因此,如果值的引用更改/突变,则会触发实际值也被更改

因此,要重置状态,必须将初始存储模块复制为值。

注销用户时,必须为每个模块分配相同的值作为副本。

这可以通过以下方式实现:

// store.js

// Initial store with modules as an object
export const initialStoreModules = {
    user,
    recruitment,
};

export default new Vuex.Store({
    /**
     * Assign the modules to the store 
     * using lodash deepClone to avoid changing the initial store module values
     */
    modules: _.cloneDeep(initialStoreModules),
    mutations: {
        // reset default state modules by looping around the initialStoreModules
        resetState(state) {
        _.forOwn(initialStoreModules, (value, key) => {
            state[key] = _.cloneDeep(value.state);
        });
        },
    }
});

然后在用户注销时呼叫commit("resetState");

答案 1 :(得分:0)

正常方法

如果用户登录,则可以添加一些布尔标志以确保用户已登录/注销。

所以最初的方法是 -

this.$store.commit('insertToken', {realtoken, isLoggedIn: true})

在vuex中,

insertToken (state, payload) {
  state.token = payload.realtoken
  state.isLoggedIn = payload.isLoggedIn
  localStorage.setItem('token', payload.realtoken)
}

当用户注销时,您应将所有标志设置为false, 在组件中 -

logout () {
    this.$store.commit('logOut')
    this.$router.replace('/login')
  }

和vuex,

logOut (state, payload) {
  state.token = null
  state.isLoggedIn = false
  localStorage.setItem('token', null)
},

通过isLoggedIntoken,您可以使用名为Navigation Guards的术语告诉路由器在哪里导航

示例 -

const checkToken = () => {

if ((localStorage.getItem('token') == null) || 
 (localStorage.getItem('token') == undefined)) {
  return false
 } else {
   return true
 }
}

// Navigation guards
if (to.path === '/') {
 if (checkToken()) {
   next()
 } else {
  router.push('/login')
 }

}

这是我在通过使用token作为与Vuex交互的一部分进行身份验证时使用的方式。

答案 2 :(得分:0)

这个扩展做得很好 https://www.npmjs.com/package/vuex-extensions

安装后,我可以在 Vuex 注销操作中调用重置

logout(context) {
  
    // do the logout stuff, such as 
    context.commit("setUser", {});

    // On logout, clear all State, using vuex-extensions
    this.reset();

    // if using router, change to login page   
    router.replace("/login");
  }

答案 3 :(得分:0)

这可能晚了,但我发现 window.localStorage.removeItem('vuex') 很有用。感谢 Thomas von Deyen,https://github.com/championswimmer/vuex-persist/issues/52#issuecomment-413913598

相关问题