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

Kong前置函数插件中无法使用lua resty.http的问题求助

解决Kong前置函数沙箱无法加载resty.http的问题

你的问题出在对Kong沙箱配置变量的理解错误,之前用的KONG_LUA_SANDBOX_GLOBALS不是用来允许加载模块的,正确的配置方式如下:

1. 修正沙箱配置,允许加载resty.http

Kong的沙箱默认限制了可加载的模块,要允许resty.http,需要用KONG_LUA_SANDBOX_REQUIRES环境变量,而不是GLOBALS:

  • 如果用容器部署,启动时设置环境变量:
    -e KONG_LUA_SANDBOX_REQUIRES=resty.http
    
  • 如果用kong.conf配置文件,添加一行:
    lua_sandbox_requires = resty.http
    

配置后重启Kong容器,让配置生效。

2. 正确编写前置校验Lua脚本

配置生效后,就可以在前置函数脚本里正常调用resty.http了,示例脚本如下:

local http = require "resty.http"
local httpc = http.new()

-- 获取请求头中的token
local token = kong.request.get_header("Authorization")
if not token then
    return kong.response.exit(401, { message = "Missing token" })
end

-- 调用外部校验接口
local res, err = httpc:request_uri("https://your-auth-server.com/validate", {
    method = "POST",
    headers = {
        ["Content-Type"] = "application/json",
        ["Authorization"] = token
    },
    body = '{}' -- 根据校验接口要求传参
})

if not res then
    return kong.response.exit(500, { message = "Auth check failed: " .. err })
end

-- 根据校验结果处理
if res.status ~= 200 then
    return kong.response.exit(403, { message = "Invalid token" })
end

-- 校验通过,继续请求

3. 验证配置是否生效

重启Kong后,执行以下命令检查沙箱配置:

kong config dump | grep lua_sandbox_requires

输出应该包含resty.http,说明配置已加载。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 11:02:07