我正在使用Vue前端、Express和Parse (parse-platform)为后端创建一个单页面应用程序。每当我对用户进行身份验证时,我都会将用户信息放入会话变量req.session.user = result;中,然后将其发送回客户机res.status(200).send(req.session);。当用户通过应用程序路由时,如何安全地检查身份验证是否有效?我担心的是,放入客户的cookies中的session id可能会被伪造,用户将被视为经过身份验证。我相信我可以向我的后端发送一个请求,检查每次用户输入路由时身份验证是否有效,但我认为这不是一个好主意,因为vue应用程序中的路由非常快,如果数百个用户快速导航可能会导致问题。我还能做什么呢?或者我做这件事/想它的方式是正确的?
我使用express-session将客户端的会话存储到他的cookie中。
app.use(session({
secret: 'secret_key',
resave: false,
saveUninitialized: true,
cookie: {} }));这是我登录用户的方式:
Parse.User.logIn(username, password).then(result => {
req.session.user = result;
res.status(200).send(req.session);
});发布于 2020-10-21 16:02:48
首先,我建议在单页面应用程序中使用状态而不是会话。
vuex = https://vuex.vuejs.org/guide/
vue-router有一个叫做beforeEach.if的函数,我们定义了这个函数,每次我们调用路由的时候都会调用它。基本上请求都要经过这个函数。
然后,我们可以在此函数中检查该用户是否已通过身份验证
例如:-
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();
}
});之后,我们定义哪个路由应该进行身份验证或不进行身份验证。Vue路由器允许我们在路由上定义一个元,这样我们就可以指定经过身份验证的路由
例如:-
{
path: "/student",
name: "student",
component: Student,
meta: {
requiresAuth: true,
},
},现在,每当有人输入"/student“url时,它都会检查该用户是否通过了身份验证。
希望这能帮助someone.good走运
https://stackoverflow.com/questions/60648647
复制相似问题