【问题标题】:How to check if user is authenticated to navigate through Vue routes?如何检查用户是否已通过身份验证以通过 Vue 路由导航?
【发布时间】:2020-06-24 04:21:48
【问题描述】:

我正在使用 Vue 前端、Express 和 Parse(解析平台)作为后端创建单页应用程序。每当我验证用户身份时,我都会将用户信息放入会话变量req.session.user = result;,然后将其发送回客户端res.status(200).send(req.session);。每当用户通过应用程序进行路由时,如何安全地检查身份验证是否有效?我担心的是,放入客户端 cookie 中的 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);
 });

【问题讨论】:

    标签: javascript vue.js express authentication express-session


    【解决方案1】:

    首先,我建议在单页应用程序中使用状态而不是会话。

    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();
      }
    });
    
    

    之后,我们定义哪个路由应该被认证或不被认证。 Vue 路由器允许我们在路由上定义一个元数据,这样我们就可以指定经过身份验证的路由

    例如:-

    {
       path: "/student",
       name: "student",
       component: Student,
       meta: {
             requiresAuth: true,
          },
     },
    
    

    现在每次有人输入“/student”网址时,它都会检查该用户是否经过身份验证。

    this is where I learned this

    希望这会对某人有所帮助。祝你好运

    【讨论】:

      猜你喜欢
      • 2022-09-29
      • 1970-01-01
      • 1970-01-01
      • 2017-07-15
      • 2018-12-21
      • 1970-01-01
      • 2018-12-28
      • 1970-01-01
      • 2017-07-10
      相关资源
      最近更新 更多