In my VueJS 3 SPA I have some routes that are protected. For example "/user"
. I use a JWT that I get from a backend. I store the JWT in a cookie. I have some functions and attributes that I have stored in a reactive access.js (simple storage).
// access.js
export const access = reactive({
isAuth: false,
setAuth(a) {
this.isAuth = a;
},
setToken(token) {
this.setAuth(true);
comhelper.setToken(token, settings); // set cookie with token
},
async getToken() {
return await comhelper.getToken(settings); // returns cookieValue by CookieName
},
});
And in my routes.js, I intercept each request and check it.
// routes.js
router.beforeEach(async (to, from, next) => {
const guarded = ['user', 'upload'];
if (guarded.filter(i => i == to.name).length > 0) {
// guarded
const t = await access.getToken()
if (t == '') {
// no token found in cookie
next();
return router.push({ name: 'login' });
}
}
next();
});
It works so far. But I wonder if this is a good solution because I'm just checking if the cookie has content. That means if I insert an arbitrary string into the cookie I would bypass this condition. Of course I wouldn't get any data from the server because the JWT would be wrong but still I wonder if there is a better solution?