GVo*_*tas 1 javascript authentication express vue.js express-session
我正在使用 Vue 前端、Express 和 Parse(解析平台)作为后端创建一个单页应用程序。每当我验证用户身份时,我都会将用户信息放入会话变量中req.session.user = result;,然后将其发送回客户端res.status(200).send(req.session);。每当用户通过应用程序路由时,如何安全地检查身份验证是否有效?我担心的是,session id放入客户端 cookie 中的内容可能会被伪造,并且用户将被视为经过身份验证。我相信我可以向后端发送一个请求,以检查每次用户输入路线时身份验证是否有效,但我认为这不是一个好主意,因为 vue 应用程序中的路由非常快,如果数百个用户快速导航可能会导致一个问题。我还能做什么?或者我是否以正确的方式做/思考它?
我用来express-session将客户的会话存储到他的 cookie 中。
app.use(session({
secret: 'secret_key',
resave: false,
saveUninitialized: true,
cookie: {} }));
Run Code Online (Sandbox Code Playgroud)
这是我登录用户的方式:
Parse.User.logIn(username, password).then(result => {
req.session.user = result;
res.status(200).send(req.session);
});
Run Code Online (Sandbox Code Playgroud)
首先,我建议在单页应用程序中使用状态而不是会话。
vuex = https://vuex.vuejs.org/guide/
vue-router 有一个名为 beforeEach 的函数。如果我们定义了这个函数,那么每次调用路由时都会调用它。基本上请求通过这个功能。
然后我们可以在此函数中检查该用户是否经过身份验证
前任:-
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();
}
});
Run Code Online (Sandbox Code Playgroud)
之后,我们定义哪些路由应该被认证或不被认证。Vue 路由器允许我们在路由上定义元,以便我们可以指定经过身份验证的路由
前任:-
{
path: "/student",
name: "student",
component: Student,
meta: {
requiresAuth: true,
},
},
Run Code Online (Sandbox Code Playgroud)
现在,每当有人输入“/student”网址时,它都会检查该用户是否经过身份验证。
希望这会对某人有所帮助。祝你好运
| 归档时间: |
|
| 查看次数: |
11713 次 |
| 最近记录: |