简体   繁体   English

在 vue.js 路由器中验证 JWT 令牌

[英]Validating JWT Token in vue.js Router

I am using the following code to generate a JWT token:我正在使用以下代码生成 JWT 令牌:

 jwt.sign(id, TOKEN_SECRET, { expiresIn: '24h' });

Once generated, I send the token to the client, which stores it within a cookie:生成后,我将令牌发送到客户端,客户端将其存储在 cookie 中:

 document.cookie = `session=${token}` + ';' + expires + ';path=/'

Furthermore, I am using vue.js Router for my navigation.此外,我正在使用 vue.js 路由器进行导航。 From my understanding, if one adds the following code in the router file, one can insert middle-ware in order to protect some routes.据我了解,如果在路由器文件中添加以下代码,可以插入中间件以保护某些路由。

 router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth) {
   let token = Vue.cookie.get('session')
   if (token == null) {
     next({
      path: '/',
      params: { nextUrl: to.fullPath }
    })
  }
 } else {
  next()
 }
})

However, I am having difficulty understanding how can one verify the validity of the JWT token using this approach, which needs to be done on the server, where the TOKEN_SECRET is stored, and not on the client side.但是,我很难理解如何使用这种方法验证 JWT 令牌的有效性,这需要在存储 TOKEN_SECRET 的服务器上完成,而不是在客户端。

Let me start with this: your goal in guarding routes is to prevent the user from having a bad experience by proceeding to a page that will attempt to retrieve information that they are not authorized to view.让我从这个开始:你保护路由的目标是通过进入一个试图检索他们无权查看的信息的页面来防止用户体验不好。

So, you don't need to validate the token on the client side.因此,您无需在客户端验证令牌。 Since a token will only be in hand if the server validated the user and returned a token, you - the author of the client code - can use the presence of the token as a means to inform what route to take the user through.由于只有当服务器验证用户并返回一个令牌时,令牌才会在手边,因此您(客户端代码的作者)可以使用令牌的存在作为通知用户通过什么路线的手段。

In other words, the client having a token is all the validation you need to allow the user through to protected routes.换句话说,拥有令牌的客户端是允许用户通过受保护路由所需的全部验证。

Remember, it is not as though a protected page has private data in and of itself.请记住,受保护的页面本身并没有私有数据。 A protected page will always retrieve that protected data from the server, which means that the server has the chance to authenticate the token after all.受保护的页面将始终从服务器检索受保护的数据,这意味着服务器毕竟有机会验证令牌。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM