Best practice for storing auth tokens in VueJS?

My backend is a REST API served by the Django-Rest-Framework. I am using VueJS for the front end and trying to figure out what works best for authentication / login. This is probably terrible code, but it works (in a component called 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
        }
    }

Does it make sense to use localStoragethis way? Also, I wonder when the user wants to log out and I call /api-token-auth/logout, do I still need to remove the token from localStorage? Actually, it’s not clear to me what happens with tokens either at the end of Django or in the / Vue browser.

+4
source share
1 answer

, , . Vuex . Vuex , , . Vuex, Vuex persisted state, 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
    }
}

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
}

Getter, :

this.$store.state.user.token

, Vue. , main.js :

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

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

Source: https://habr.com/ru/post/1682543/


All Articles