You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Fastify如何为preHandler传递自定义参数(权限校验场景)

在Fastify中为preHandler传递自定义scopes参数实现权限校验

核心思路

把原来的jwtVerify从固定的preHandler函数改成工厂函数——让它接收scopes参数,再返回真正的preHandler逻辑函数。这样在路由配置时就能传入自定义权限范围,返回的函数会通过闭包持有这些参数,执行时就能用来做权限校验。


步骤1:修改jwtVerify插件的实现

调整插件里的decorate逻辑,改成工厂函数模式:

const jwtVerifyPlugin: FastifyPluginAsync = async (fastify: FastifyInstance, options: FastifyPluginOptions) => {
    // 改成工厂函数,接收需要校验的scopes参数
    fastify.decorate('jwtVerify', function (requiredScopes?: string[]) {
        // 返回实际的preHandler函数
        return async function (request: FastifyRequest, reply: FastifyReply) {
            // 1. 先执行原有JWT校验逻辑
            // 示例:如果用@fastify/jwt插件,先解析令牌
            const payload = await request.jwtVerify();
            // (这里替换成你实际的JWT校验代码,确保能拿到用户的权限信息)

            // 2. 若传入了scopes,执行权限范围校验
            if (requiredScopes && requiredScopes.length > 0) {
                // 假设用户的权限列表存在于payload的scopes字段中
                const userScopes = payload.scopes || [];
                
                // 检查用户是否拥有所有要求的权限
                const hasPermission = requiredScopes.every(scope => userScopes.includes(scope));
                if (!hasPermission) {
                    reply.code(403).send({ error: 'Forbidden', message: '权限不足' });
                    return;
                }
            }
        };
    });
};

步骤2:在路由配置中传入scopes参数

路由里调用jwtVerify时直接传入需要的权限范围数组:

this.fastify.get('/ping', {
    preHandler: [
        // 传入需要的权限范围,比如['admin', 'config:read']
        this.fastify.jwtVerify(['admin', 'config:read']),
    ],
}, this.configHandler.getConfiguration.bind(this.configHandler));

步骤3:适配无权限校验的场景

如果只需要JWT校验、不需要权限范围限制,直接调用空参数即可:

this.fastify.get('/public-data', {
    preHandler: [
        this.fastify.jwtVerify(), // 不传scopes,仅做JWT合法性校验
    ],
}, someHandler);

内容的提问来源于stack exchange,提问作者Materno

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 15:12:48