After following numerous Vue.js tutorials, I have encountered a dilemma. Imagine I am constructing a single-page application where a user can log in and access data through a RESTful API.
The initial step involves sending login credentials (username and password) to the API to receive an authentication token. This token is then stored in Vuex as well as local storage or cookies to maintain the user's logged-in status even after a page refresh.
All subsequent API requests are authenticated using this token.
My routes are configured as follows:
const routes = [
{
path: '/dashboard', name: 'dashboard', component: Dashboard, meta: { requiresAuth: true }
},
{
path: '/login', name: 'Login', component: Login,
},
]
I utilize a route guard to prevent non-logged-in users from accessing the /dashboard page:
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
if (!store.getters.loggedIn) {
next({ path: "/login" })
} else {
next();
}
} else {
next();
}
})
However, my concern lies with the implementation of the loggedIn getter in the Vuex store:
const getters = {
loggedIn(state) {
return state.token !== null;
}
};
Although everything appears to be functioning correctly, there is a security vulnerability. By manipulating the access_token value in local storage using developer tools, one could gain unauthorized access to the /dashboard page upon refreshing.
This leads me to question how to prevent this scenario. One potential solution is to split the application into two pages - a login page for authentication performed server-side via sessions, and a separate SPA accessible only to authenticated users.
Alternatively, is there a standard method for addressing this issue within a SPA environment?