我只是在学习fastify,我不知道如何实现我想要的:我有这样的路线:
this.fastify.get('/ping', {
preHandler: [
this.fastify.jwtVerify,
],
}, this.configHandler.getConfiguration.bind(this.configHandler));
预处理程序确实会被执行,并包含已知的参数,如请求和回复。
我想将一个自定义参数传递给我的preHandler函数。目前,preHandler正在验证在auth报头中传递的jwt令牌。我想要实现的是将作用域传递给处理程序,而处理程序也可能被检查。
我的preHandler目前是这样注册的插件:
const jwtVerifyPlugin: FastifyPluginAsync = async (fastify: FastifyInstance, options: FastifyPluginOptions) => {
fastify.decorate('jwtVerify', async function (request: FastifyRequest, reply: FastifyReply) {
//jwtVerficiation happens here
//scope verification should follow
})
}
因此,总的来说:我必须在路径的某个地方添加作用域,并且必须将这些作用域放到我的preHandler中的某个位置。
知道我怎么能做到吗?
谢谢!
发布于 2022-09-09 18:12:16
您可以像这样定义您的装饰功能:
const jwtVerifyPlugin: FastifyPluginAsync = async (fastify: FastifyInstance, options: FastifyPluginOptions) => {
fastify.decorate('jwtVerify', function (options?: { scopes?: string[] }) {
return async function (request: FastifyRequest, reply: FastifyReply, done: HookHandlerDoneFunction) {
if (options?.scopes) {
// access scopes here
}
done();
};
})
}
然后像这样使用它:
this.fastify.get('/ping', {
preHandler: [
this.fastify.jwtVerify({ scopes: ['admin'] }),
],
}, this.configHandler.getConfiguration.bind(this.configHandler));
https://stackoverflow.com/questions/73545471
复制相似问题