When it comes to authorizing actions and accessing protected resources from my backend, I rely on jwt tokens for security. Here is an overview of the technologies used in both the frontend and backend:
Frontend: Vue, Vue Router, VueX, Vuetify
Backend: Express, jwt tokens, cookieParser
After successfully calling the login route, the frontend receives an accessToken along with user data such as username, email, and userId. In addition, a httpOnly cookie containing the refreshToken is sent back and stored in the database. The vuex store is then updated to reflect the user's logged-in status and information, while also saving the user object to localStorage.
To ensure seamless auto-login functionality when reopening tabs or windows, the vuex store is initiated with user data retrieved from the localStorage at the beginning.
// read out localStorage for the user
const user = JSON.parse(localStorage.getItem('user'));
const initialState = user
? { user, loggedIn: true, accessToken: null }
: { user: null, loggedIn: false, accessToken: null };
Prior to accessing any protected routes, the vue router's beforeEach
method is utilized to check if the vuex getter auth/getUser
returns a valid user object. If not, the router redirects to the login page for re-authorization.
const routes = [
{ path: '/login', name: 'Login', component: Login, meta: { authRequired: false }},
{ path: '/home', name: 'Home', component: Home, meta: { authRequired: true }}
]
const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes });
router.beforeEach(async (to, from, next) => {
if (to.meta.authRequired) {
let user = VuexStore.getters['auth/getUser'];
if (!user) {
next({ path: '/login'});
}
}
next();
});
There is a concern about the validity of the user object stored in the localStorage and whether relying solely on that for auto-login is secure enough. Should the received accessToken or the cookie with the refreshToken be used in some way for the auto-login process instead? Your insights are appreciated. Thanks!