I have a VueJS app with Vuetify framework, which connects to a Jhipster Java backend.
I used Vuex to store the user authentication token with the help of this tutorial, storing the token on localStorage
.
My problem is that whenever i duplicate the tab i'm working on, the beforeEach
function is fired twice and clears the token on the second execution and directs to login page, same applies if i close the tab and tries to re open it.
Here is my code when the user logs in in store.js
:
login({commit}, user){
return new Promise((resolve, reject) => {
commit('auth_request');
axios({
method: 'POST',
url: api.AUTHENTICATE,
data: user,
})
.then(response => {
const token = response.data.id_token;
localStorage.setItem('token', token)
axios.defaults.headers.common['Authorization'] = 'Bearer '+token;
commit('auth_success', token);
resolve(response)
})
.catch(error => {
commit('auth_error')
localStorage.removeItem('token')
reject(error)
})
});
},
then my code in main.js
to check is the token is present:
Vue.prototype.$http = Axios;
const token = localStorage.getItem('token')
if (token) {
console.log("token exists")
Vue.prototype.$http.defaults.headers.common['Authorization'] = token;
}
else{
console.log("no token");
}
the beforeEach
function in vue-router
:
router.beforeEach((to, from, next) => {
let currentUser = store.getters.isLoggedIn;
let requiresAuth = to.matched.some(record => record.meta.requiresAuth);
console.log("to: "+to.path+" user: "+currentUser+ " auth: "+requiresAuth);
if (requiresAuth && currentUser){
console.log("logged: "+store.state.token);
next();
}
else if (requiresAuth && !currentUser){
console.log("not logged: "+store.state.token);
next('/login');
}
else if (!requiresAuth && currentUser){
console.log("rediect: "+store.state.token);
next('/dashboard');
}
else{
console.log("exception")
next();
}
})
When ever i log into the app, i get the token and redirected to dashboard page:
to: /dashboard user: true auth: true
logged: eyJhbGciOiJ....
but when i duplicate the tab or close and reopen the tab: i get this:
token exists
to: /dashboard user: true auth: true
logged: eyJhbGciOiJIUzUxM...
to: /login user: false auth: false
exception
i noticed that the beforeEach
is executed twice. If i try to refresh the first page after this, the token is cleared and i am redirected to login.