在VueJS中存储auth令牌的最佳实践?

Eva*_*mir 10 authentication django django-rest-framework vuejs2

我的后端是由Django-Rest-Framework提供的REST API.我正在使用VueJS作为前端,并试图找出进行身份验证/登录的最佳实践.这可能是可怕的代码,但它可以工作(在一个名为的组件中Login.vue):

    methods: {
        login () {
            axios.post('/api-token-auth/login/', {
                username: this.username,
                password: this.pwd1
            }).then(response => {
                localStorage.setItem('token', response.data.token)
            }).catch(error => {
                console.log("Error login")
                console.log(error)
            })
            this.dialog = false
        }
    }
Run Code Online (Sandbox Code Playgroud)

使用localStorage这种方式有意义吗?此外,我想知道用户何时想退出,我打电话/api-token-auth/logout,我是否还需要从中删除令牌localStorage?实际上,我不清楚Django端或者浏览器/ Vue上的令牌是什么.

For*_*ame 11

应用程序范围的数据(例如身份验证和用户信息)应进入集中状态.您可以使用Vuex或简单的共享状态.Vuex很棒,但它确实增加了复杂性,所以你必须计算成本.如果使用Vuex,则可以使用Vuex持久状态将其保留在localStorage中.这应该比localStorage快得多.根据我的经验,localStorage不可靠并且可能导致问题.国家是要走的路.

例如,修改当前代码以将其发送到Vuex:

    methods: {
    login () {
        axios.post('/api-token-auth/login/', {
            username: this.username,
            password: this.pwd1
        }).then(response => {
            that.$store.commit('LOGIN_SUCCESS', response)
        }).catch(error => {
            console.log("Error login")
            console.log(error)
        })
        this.dialog = false
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在Vuex中(如果使用模块,则像/store/modules/user.js):

Vue.use(Vuex)
const state = { token: null}
const mutations = {

LOGIN_SUCCESS(state, response) {
    state.token = response.token
}
export default {
    state,
    mutations
}
Run Code Online (Sandbox Code Playgroud)

并通过Getter或直接调用令牌:

this.$store.state.user.token
Run Code Online (Sandbox Code Playgroud)

这假设存储由Vue使用.例如,在main.js中你将拥有:

import store from './store/index.js'

new Vue({
  el: '#app',
  store
})
Run Code Online (Sandbox Code Playgroud)

  • 你不应该存储敏感信息是的,但令牌不是密码意义上的敏感信息,如果它的寿命足够短,我看不到安全问题。甚至 cookie 也可能受到损害。如果您需要超级安全的系统,深度防御会有所帮助。 (5认同)
  • ❌ **注意**:不要使用 localStorage,因为它可以被 JS 访问。如果您打算使用 `vue-persistedstate`,请确保将存储更改为使用 cookie。它的默认存储是 localStorage,因此存储敏感数据是不安全的。带有 `httpOnly` 标志的 Cookie 比 localStorage 更安全。 (4认同)