2017-07-29 266 views
3

我的后端是一个由Django-Rest-Framework提供的REST API。我正在使用VueJS作为前端,并试图找出进行身份验证/登录的最佳做法。这可能是可怕的代码,但它的工作原理(在一个叫Login.vue分量):在VueJS中存储身份验证令牌的最佳做法?

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 
     } 
    } 

是否有意义使用localStorage这种方式?另外,我想知道用户何时需要注销,并且我拨打/api-token-auth/logout,我是否还需要从localStorage中删除令牌?实际上我并不清楚Django最终或者浏览器/ Vue中的令牌有什么变化。

回答

2

应用程序范围内的数据(如身份验证和用户信息)应该进入集中状态。您可以使用Vuex或a simple shared state。 Vuex非常棒,但它增加了复杂性,所以你必须计算成本。如果您使用Vuex,则可以使用Vuex persisted state将其保存在localStorage中。这应该比localStorage快得多。根据我的经验,localStorage不可靠,可能会导致问题。国家是要走的路。以上(如果使用模块等/store/modules/user.js)

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 
    } 
} 

然后在Vuex:

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

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

LOGIN_SUCCESS(state, response) { 
    state.token = response.token 
} 
export default { 
    state, 
    mutations 
} 

并通过Getter或直接呼叫令牌:

this.$store.state.user.token 

这个假设商店被Vue使用。例如,在main.js中,您将拥有:

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

new Vue({ 
    el: '#app', 
    store 
}) 
+0

谢谢!我也要检查持久状态。 –

相关问题