user3714932
user3714932

Reputation: 1353

Vuex persist authenticated status

I'm using Vuex and Laravel sanctum to authenticate users. The following is my Vuex auth.js

import axios from 'axios'

export default {

    namespaced: true,

    state:{
        authenticated: false,
        user: null
    },

    getters:{
        authenticated (state) {
            return state.authenticated
        },

         user (state) {
            return state.user
        }
    },

    mutations:{
        SET_AUTHENTICATED(state, value){
            state.authenticated = value
        },

        SET_USER(state, data){
            state.user = data
        }
     },

    actions:{
        async login ({commit}, credentials){
         await axios.get('/sanctum/csrf-cookie')
          await axios.post('/api/login', credentials).then(response => {
                commit('SET_AUTHENTICATED', true)
                commit('SET_USER', response.data)
            }).catch(() => {
                commit('SET_AUTHENTICATED', false)
                commit('SET_USER', null)
            })

        },


    }

}

The authentication is working but everytime I refresh the page the authentication status is defaulted back to false. How do I ensure that if the user is authenticated the authentication status remains true?

Upvotes: 0

Views: 996

Answers (3)

Bas van Ingen
Bas van Ingen

Reputation: 3

@studio-pj. I don't think it is safe to store a token in LocalStorage because it are user credentials. Everywhere i read about LocalStorage is that it shouldn't be used for login credentials and other security sensitive data.

Upvotes: 0

studio-pj
studio-pj

Reputation: 874

Assuming you're getting back a token from your API, you could store this in the local storage.

state: {
    authenticated: false,
    user: null,
    token: localStorage.getItem('token') || '',
},
actions:{
    await axios.post('/api/login', credentials).then(response => {
        const token = response.data.token
        localStorage.setItem('token', token)
    })
}

You could handle an expired token via Axios interceptors:

created () {
    this.$axios.interceptors.response.use(undefined, function (err) {
        return new Promise(function (resolve, reject) {
        if (err.status === 401) {
          this.$store.dispatch(logout)
        }
        throw err;
      });
    });
}

Vuex logout action

logout({commit}){
  return new Promise((resolve, reject) => {
    commit('logout')
    localStorage.removeItem('token')
    delete axios.defaults.headers.common['Authorization']
    resolve()
  })
}

Upvotes: 1

EricHier
EricHier

Reputation: 455

There are two possible options to persist data: you could use cookies or local storage. Both options are frequently used, for example by Nuxt Auth.

An easy option to persist the store would be to use vuex-persist. You can find the getting started guide here.

Upvotes: 2

Related Questions