vue.js - 在 Front 中安全存储用户角色的位置

标签 vue.js vuex vue-router

我正在开发一个 Vuejs 应用程序,当用户成功登录时,后端仅返回一个 token 。

我想要做的是将用户的角色存储在某个地方,以便在路由器的 beforeEnter() 中使用它。

当用户登录时,请求会获取用户信息(带有角色)。但是当我刷新页面或更改路线时,我会丢失状态。

我本来打算将用户信息放在 LocalStage 中,但我很确定它根本不安全,因为我可以在应用程序中编辑角色(在 Chrome 中)..

我需要在路由器中始终保持该角色可用,但除了本地存储之外我不知道如何实现

有什么解决办法吗?

编辑:因为我只从后端得到了一个 token 作为响应。直接调用另一个请求来获取用户数据(包括角色)好吗?

像这样:

export function loginUser ({ commit }, payload) {
    return new Promise(resolve => {
    LoginService.login(payload)
      .then(data => {
          console.log('enter')
          console.log(data)
            let tkn = data.access_token
            Cookies.set('tkn', tkn.toString())
            Cookies.set('cntd', 'true')
     --->   UserService.getB2cUserProfile()
            .then(data => {
                commit('LOGIN_USER', data)
                // will commit the data here to change the userInfos state
                resolve(data)

            })
      })
      .catch(err => {
        console.log(err)
      })
    })
}

最佳答案

你应该选择 vuexvue-persistedstate如果您借助与您的状态同步的 cookie 刷新页面,则状态保持不变,因此每当任何状态发生变化时,它都会在 cookie 中自动更改,并帮助您实现您想要的功能(路由和在线)刷新)。当您在登录后获得 token 时,您可以设置状态,并使用持久性状态,您可以在要为当前登录用户保存的路径中提及状态。这可以为您提供很大帮助,因为在用户从您的网站注销后,您可以再次将角色和其他状态设置为默认值。 因此,在 vuex 的商店中,您可以执行以下操作:-

import Vue from 'vue';
import Vuex from 'vuex';
import createPersistedState from "vuex-persistedstate";
import * as Cookies from "js-cookie";

Vue.use(Vuex);
export const store = new Vuex.Store({
    state: {
        auth: "false",
        role: "",
        anyotherproperty:""
    },
    getters: {
        getRole: state => {
            return state.role;
        },
        getAuth: state => {
            return state.auth;
        },
    },
    plugins: [
        createPersistedState({
            paths: ['auth', 'role'],
            storage: {
                getItem: (key) => Cookies.get(key),
                setItem: (key, value) =>
                    Cookies.set(key, value, { expires: 7}),
                removeItem: (key) => Cookies.remove(key),
            },
        }),
    ],
    mutations: {
        //mutation will change the states like auth and role
    },
    actions: { //your actions which commit a mutation
    }

});

然后,在路由器中,您可以使用 vuex 中定义的全局状态并检查用户角色是 A 还是 B 还是默认,以及 auth 是 true 还是 false。 这将帮助您很好地管理一切。

关于vue.js - 在 Front 中安全存储用户角色的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65163483/

相关文章:

vue.js - 未捕获的引用错误 : VueRouter is not Defined

javascript - View |如何将Web端口号更改为80?

javascript - 我如何能够在 vue js html 中以给定格式多次选择和传递数据?

laravel - 护照,过期后刷新 token 的方法

vue.js - 是否可以根据 "el"找到 Vue 组件?

javascript - 根据条件语句vuejs更改img src

Vuex - 绑定(bind)助手中的动态命名空间(mapState,...)

vue.js - 使用 Apollo for Nuxt.js SSR 预取 API 数据

javascript - Vue 和 Vuex 在 store 模块内进行 Axios 操作

vue.js - Vuex 正在重置已设置的状态