Reputation: 31
I'm creating a Single Page Application using Vue front-end, Express and Parse (parse-platform) for back-end. Whenever I authenticate user, I put user's info into session variable req.session.user = result;
and then send it back to the client res.status(200).send(req.session);
. Whenever user is routing through application, how do securely check if authentication is valid? What I am afraid of, is that the session id
that is put into client's cookies could be forged and user would be treated as authenticated. I believe I could send a request to my back-end to check if authentication is valid every time user enters a route but I believe this is not a great idea as routing in vue applications are very quick and if hundreds of users navigating quickly could cause a problem. What else could I do? Or am I doing it/thinking of it the right way?
I use express-session
to store client's session into his cookies.
app.use(session({
secret: 'secret_key',
resave: false,
saveUninitialized: true,
cookie: {} }));
This is how I login user:
Parse.User.logIn(username, password).then(result => {
req.session.user = result;
res.status(200).send(req.session);
});
Upvotes: 2
Views: 14319
Reputation: 2452
first of all, I recommend using state rather than a session in a single page application.
vuex = https://vuex.vuejs.org/guide/
vue-router have a function called beforeEach.if we defined this function,it's called every time when we call a route. basically request go through this function.
then we can check this user is authenticated or not in this function
ex:-
let router = new Router({
mode: "hash", // https://router.vuejs.org/api/#mode
linkActiveClass: "active",
scrollBehavior: () => ({ y: 0 }),
routes: configRoutes(), // im using function to define all the routes. you can define routes here
});
router.beforeEach((to, from, next) => {
if (to.matched.some((record) => record.meta.requiresAuth)) {
if (localStorage.getItem("userToken") == null) {
next({
path: "/login",
params: { nextUrl: to.fullPath },
});
} else {
if (!store.state.isAuthenticated) {
next({
path: "/login",
params: { nextUrl: to.fullPath },
});
} else {
next();
}
}
} else {
next();
}
});
after that, we define which route should be authenticated or not. Vue router allows us to define a meta on our routes so we can specify the authenticated routes
ex:-
{
path: "/student",
name: "student",
component: Student,
meta: {
requiresAuth: true,
},
},
now everytime someone enter "/student" url it's gonna check if that user authenticated or not.
hope this will help someone.good luck
Upvotes: 7