首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Fastify REST-API Auth插件不触发为preHandler

Fastify REST-API Auth插件不触发为preHandler
EN

Stack Overflow用户
提问于 2019-01-13 23:44:06
回答 2查看 2.4K关注 0票数 1

我建立了一个Fastify Rest-Api,并编写了一个插件来封装基于JWT的身份验证逻辑。我在我想要保护的每一条路由上都使用preHandler钩子,但是似乎preHandler或我的插件被忽略了,因为我完全可以在没有令牌的情况下发出请求并获取数据。

我查找了所有文档,但仍然无法运行。如果我只是console.log()函数fastify.authenticate,则会得到一个未定义的函数。

这是我的插件customJwtAuth:

代码语言:javascript
复制
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文件中注册了这样的插件:

代码语言:javascript
复制
  const customJwtAuth = require('./plugin/auth')
  fastify.register(customJwtAuth).after(err => {if (err) throw err})

然后,我像这样将我的函数应用于路由:

代码语言:javascript
复制
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就不应该返回任何数据。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-02-06 13:55:06

这里给你一个有用的例子。

注意,当您注册错误的装饰器时,您正在调用next()

您的主要错误是由于[fastify.authenticate]行造成的,因为在那个fastify实例中没有装饰器。

代码语言:javascript
复制
//### 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' })
代码语言:javascript
复制
//### 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)

你得到:

代码语言:javascript
复制
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
票数 3
EN

Stack Overflow用户

发布于 2019-02-19 15:53:24

如果您正在使用fastify的第2版,您可以使用PreHandler,如果您不需要使用beforeHandler,也需要为类似的东西更改路线

代码语言:javascript
复制
//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')
)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54174260

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档