简体   繁体   English

在 Nuxt.js 中,如何仅将某些路由限制为具有有效 JWT 令牌的客户端?

[英]In Nuxt.js how do you restrict some routes only to clients with a valid JWT token?

In Nuxt.js this is one way to implement authentication:Nuxt.js 中,这是实现身份验证的一种方法:

  1. The client authenticates by sending an HTTP request with its credentials in the body to an API route of the Nuxt backend;客户端通过向 Nuxt 后端的 API 路由发送 HTTP 请求及其正文中的凭据来进行身份验证;
  2. The Nuxt backend responds with a JWT token that allows the client to access protected routes; Nuxt 后端使用JWT 令牌进行响应,该令牌允许客户端访问受保护的路由;
  3. Finally, when the authenticated user tries to access such a route, they make an HTTP request to the Nuxt backend with their JWT token inserted in the header;最后,当经过身份验证的用户尝试访问此类路由时,他们会向 Nuxt 后端发出 HTTP 请求,并将其 JWT 令牌插入 header;
  4. The backend validates the JWT token and responds with the requested page JSON data to the client.后端验证 JWT 令牌并使用请求的页面 JSON 数据响应客户端。

What I don't understand is how to make the Nuxt backend aware that for some protected routes it has to check the JWT token of the client before providing the page JSON data.我不明白的是如何让 Nuxt 后端意识到对于某些受保护的路由,它必须在提供页面 JSON 数据之前检查客户端的 JWT 令牌。 I mean, where exactly in Nuxt can I implement this kind of validation?我的意思是,我可以在Nuxt的哪个地方实现这种验证?

Well i am confused a bit first you say API data the other sentece you say JSON page.. however.好吧,我首先有点困惑,你说 API 数据另一个句子你说 JSON 页面.. 但是。 If you want to protect an PAGE then you create an middleware如果要保护 PAGE,则创建中间件

middleware/auth.js中间件/auth.js

export default async function ({ store, $axios, redirect }) {
  let valid = await $axios.$post('/api/checktoken')
  if (!valid) {
    redirect('/')
  }
}

You need to create an API where you check the token.您需要创建一个 API 来检查令牌。 Usually you need to put the token in your header like Authentication: Bearer token... however i simply save my token inside an cookie.通常您需要将令牌放入您的 header 中,例如Authentication: Bearer token...但是我只是将令牌保存在 cookie 中。 Because if you send an HTTP request to the server the cookies gets automatically sended with it so i dont need to do some extra work.因为如果您向服务器发送 HTTP 请求,cookies 会自动发送,所以我不需要做一些额外的工作。

Next step is you go to some page and set your middleware auth.下一步是将 go 设置到某个页面并设置中间件身份验证。

page.vue页面.vue

<script>
export default {
   middleware: "auth"
}
</script>

However if you want to protect some backend routes you can do it like this.但是,如果你想保护一些后端路由,你可以这样做。 Create again an middleware再次创建中间件

  async authenticate(req, res, next) {
    let token = await cookieService.getTokenFromCookie(req)
    if (!token) return errorService.resError(res, 400, 'Authorization failed')
    let tokenValid = await tokenService.verifyToken(token)
    if (!tokenValid)
      return errorService.resError(res, 400, 'Authorization failed')
    let decodedData = tokenService.decode(token)
    if (!decodedData)
      return errorService.resError(res, 400, 'Authorization failed')
    res.locals.userId = decodedData.userId
    res.locals.role = decodedData.role
    next()
  }

In this case you basically need to read the token out of your cookie.在这种情况下,您基本上需要从 cookie 中读取令牌。 (in case you dont use cookies you will need to read it out of your header so for this you should create an function that reads your token out of the header) (如果你不使用 cookies 你需要从你的 header 中读取它,所以为此你应该创建一个 function 来读取你的令牌)

Check if token is even there.检查令牌是否在那里。

Verify if token is valid.验证令牌是否有效。

Decode the token so you can access the data in it解码令牌,以便您可以访问其中的数据

Now you can also put the data to your res.locals .现在您还可以将数据放入您的res.locals中。 The advantage is that this data is scoped to this current request and you can access it in the next middleware / endpoint.优点是此数据的范围仅限于当前请求,您可以在下一个中间件/端点中访问它。

then you call next() to step to the next middleware / endpoint然后你调用next()进入下一个中间件/端点

function endpoint(req, res) {
   let { userId, role } = res.locals
   do something....
}

So the route looks something like this:所以路线看起来像这样:

app.use("/some/api/point", authenticate, endpoint)

The good thing about is you can put authenticate in every API route you want to protect.好处是您可以在要保护的每个 API 路由中添加authenticate

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

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