My VueJS single-page application uses JWT authentication for users.
I am currently working on ensuring that users remain authenticated after a page reload. If the user is not authenticated, they should be redirected to the login page.
The access token and refresh token are stored in both cookies and Vuex:
Vuex.state:
auth: {
user: {},
isAuthenticated: false,
accessToken: null,
refreshToken: null
}
Vuex.actions.refreshToken
refreshToken: async ({state, commit, dispatch}) => {
try {
await api.jwtRefresh(state.auth.refreshToken).then(response => {
if (response.status === 200) {
dispatch("setAuthData",{
accessToken:response.data.access,
isAuthenticated:true
})
}
}).catch(err => {
dispatch('logout')
});
} catch (e) {
dispatch('logout')
}
}
In App.vue:
export default {
data: () => ({}),
mounted() {
this.$store.dispatch('setAuthDataFromCookies')
this.$store.dispatch('refreshToken') // checks if user is authenticated, redirect to login page if not
this.$router.push('/dashboard')
}
}
To tackle the issue of immediate redirection before the token is refreshed, I aim to confirm the token validity first. Upon successful refreshing of the JWT token, the user can proceed to /dashboard. In case of failure, the user will be redirected to /login.
The challenge arises from the fact that the mounted method doesn't wait for the refreshToken action to finish its execution before redirecting the user to /dashboard.
How can I resolve this so that the refreshToken action completes before any redirection? My intention is for the refreshToken action to redirect the user to /login upon encountering an error.