Fastify REST-API JWT-Auth 插件未作为预处理器触发
Fastify REST-API JWT-Auth Plugin not firing as preHandler
我正在设置一个 Fastify Rest-Api 并编写了一个插件来封装我基于 JWT 的身份验证逻辑。我在我想保护的每条路线上都使用了 preHandler Hook,但似乎 preHandler 或我的插件被忽略了,因为我可以在没有令牌的情况下发出请求并获取数据。
我查阅了每一篇文档,但仍然无法理解运行。如果我只是 console.log() 我的函数 fastify.authenticate 我得到一个 undefined.
这是我的插件 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 不应该 return 任何数据。
给你一个工作示例。
请注意,您在注册错误的装饰器时调用了 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')
)
我正在设置一个 Fastify Rest-Api 并编写了一个插件来封装我基于 JWT 的身份验证逻辑。我在我想保护的每条路线上都使用了 preHandler Hook,但似乎 preHandler 或我的插件被忽略了,因为我可以在没有令牌的情况下发出请求并获取数据。
我查阅了每一篇文档,但仍然无法理解运行。如果我只是 console.log() 我的函数 fastify.authenticate 我得到一个 undefined.
这是我的插件 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 不应该 return 任何数据。
给你一个工作示例。
请注意,您在注册错误的装饰器时调用了 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')
)