簡體   English   中英

固定REST-API JWT-Auth插件不作為preHandler觸發

[英]Fastify REST-API JWT-Auth Plugin not firing as preHandler

我設置了Fastify Rest-Api並編寫了一個插件來封裝基於JWT的身份驗證邏輯。 我在我想保護的每條路由上使用了preHandler Hook,但是由於我可以在沒有令牌的情況下發出請求並獲取數據,因此preHandler或我的插件似乎被忽略了。

我查閱了所有文檔,但仍然無法運行。 如果我只是console.log()我的函數fastify.authenticate我得到一個未定義。

這是我的插件customJwtAuth:

const fp = require('fastify-plugin')

async function customJwtAuth(fastify, opts, next) {

//register jwt 
 await fastify.register(require('fastify-jwt'),
    {secret: 'asecretthatsverylongandimportedfromanenvfile'})

fastify.decorate('authenticate', async function(request, reply) {
 try {
   const tokenFromRequest = request.cookies.jwt

  await fastify.jwt.verify(tokenFromRequest, (err, decoded) => {
     if (err) {
       fastify.log.error(err)
       reply.send(err)
    }
     fastify.log.info(`Token verified: ${decoded}`)
  })
  } catch (err) {
  reply.send(err)
  fastify.log.error(err)
  }
 })
next()
}

module.exports = fp(customJwtAuth, {fastify: '>=1.0.0'})

我將這樣的插件注冊到主server.js文件中:

  const customJwtAuth = require('./plugin/auth')
  fastify.register(customJwtAuth).after(err => {if (err) throw err})

然后我將這樣的功能應用於路線:

const fastify = require('fastify')
const productHandler = require('../handler/productHandler')

const productRoutes = [
  {
  method: 'GET',
  url: '/api/product',
  preHandler: [fastify.authenticate],
  handler: productHandler.getProducts
  }, ... ]

如果請求中不包含簽名的jwt或根本沒有jwt,則api不應該返回任何數據。

這里給你一個工作的例子。

請注意,您在注冊錯誤的裝飾器時調用了next()

您的主要錯誤歸因於[fastify.authenticate]行,因為在該fastify實例中沒有裝飾器。

//### customAuthJwt.js

const fastifyJwt = require('fastify-jwt')
const fp = require('fastify-plugin')

async function customJwtAuth(fastify, opts, next) {
  fastify.register(fastifyJwt, { secret: 'asecretthatsverylongandimportedfromanenvfile' })
  fastify.decorate('authenticate', async function (request, reply) {
    try {
      // to whatever you want, read the token from cookies for example..
      const token = request.headers.authorization
      await request.jwtVerify()
    } catch (err) {
      reply.send(err)
    }
  })
}

module.exports = fp(customJwtAuth, { fastify: '>=1.0.0' })

//### server.js
const fastify = require('fastify')({ logger: true })
const customJwtAuth = require('./customAuthJwt')

fastify.register(customJwtAuth)

fastify.get('/signup', (req, reply) => {
  // authenticate the user.. are valid the credentials?
  const token = fastify.jwt.sign({ hello: 'world' })
  reply.send({ token })
})


fastify.register(async function (fastify, opts) {
  fastify.addHook('onRequest', fastify.authenticate)
  fastify.get('/', async function (request) {
    return 'hi'
  })
})

fastify.listen(3000)

你得到:

curl http://localhost:3000/
{"statusCode":401,"error":"Unauthorized","message":"No Authorization was found in request.headers"}

curl http://localhost:3000/signup
{"token": "eyJhbGciOiJIUzI1NiI..."}

curl 'http://localhost:3000/' -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiI...'
hi

如果您使用的是fastify的第2版,則可以使用PreHandler,如果不需要,則需要使用beforeHandler,此外,還需要更改此類路由

//routes/products.js
const fastify = require('fastify')
const productHandler = require('../handler/productHandler')

module.exports = function (fastify, opts, next) {
    fastify.route({
     method: 'GET',
     url: 'api/product',
     beforeHandler: fastify.auth([
      fastify.authenticate
     ]),
     handler: productHandler.getProducts
    })
    ......
  next()
}

//server.js
....
fastify.register(require('fastify-auth'))
       .register(customJwtAuth)

const customJwtAuth = require('./customAuthJwt')

....
fastify.register(
 require('./routes/products')
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM