简体   繁体   中英

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:

  1. The client authenticates by sending an HTTP request with its credentials in the body to an API route of the Nuxt backend;
  2. The Nuxt backend responds with a JWT token that allows the client to access protected routes;
  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;
  4. The backend validates the JWT token and responds with the requested page JSON data to the client.

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. I mean, where exactly in Nuxt can I implement this kind of validation?

Well i am confused a bit first you say API data the other sentece you say JSON page.. however. If you want to protect an PAGE then you create an middleware

middleware/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. Usually you need to put the token in your header like Authentication: Bearer token... however i simply save my token inside an 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.

Next step is you go to some page and set your middleware auth.

page.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. (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)

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 . 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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