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

Kong插件access阶段未执行及JWT转URI功能实现求助

Kong Plugin Access Phase Not Executing: Troubleshooting & Fixes

Let's break down why your plugin's access phase isn't running, and fix the code step by step.

Core Issue: Incorrect Module Return Position

The biggest problem is that you placed return CtkHandler inside the access method instead of at the very end of your main plugin file. Kong needs the plugin class to be returned at the module level to properly load and execute its lifecycle methods (like access). This is why only your initialization logs are showing up—Kong never properly registered the plugin's access hook.

Fix 1: Correct Main Plugin Structure

Here's the revised main plugin code with critical fixes:

local BasePlugin = require "kong.plugins.base_plugin"
local access = require "kong.plugins.ctk.access"
local responses = require "kong.tools.responses"

local CtkHandler = BasePlugin:extend()

CtkHandler.PRIORITY = 3505
CtkHandler.VERSION = "0.1.0"

-- Helper for consistent logging (replace with ngx.log for Kong's native logs if preferred)
local function log_msg(msg)
  local file = io.open("/usr/local/kong/logs/ctk.lua", "a+")
  if file then
    file:write(msg .. "\n")
    file:close()
  end
end

log_msg("--- JUST EXTENDED THE BASE PLUGIN ---")

function CtkHandler:new()
  CtkHandler.super.new(self, "ctk")
  log_msg("--- INSTACIATED ITSELF ---")
  return self -- Critical: return the instance to complete initialization
end

function CtkHandler:access(conf)
  CtkHandler.super.access(self)
  log_msg("--- STARTED THE ACCESS PART ---")

  -- Call the authentication logic from your access module
  local ok, err = access.do_authentication(conf)
  if not ok then
    return responses.send(err.status, err.message)
  end
end

-- Move return to the END of the module
return CtkHandler

Fix 2: Access Module Errors

Your access module had several syntax and logic issues that would have broken functionality even if the access phase ran:

Key Issues in the Original Access Code:

  • No execute function (you tried calling access.execute(conf) but it didn't exist)
  • do_authentication didn't properly handle return values or pass the conf parameter
  • append_uri had a syntax error (ngx.get_uri_args missing parentheses) and incorrect URI modification logic

Here's the fixed access module:

local responses = require "kong.tools.responses"
local ngx_re_gmatch = ngx.re.gmatch

local function log_msg(msg)
  local file = io.open("/usr/local/kong/logs/ctk.lua", "a+")
  if file then
    file:write(msg .. "\n")
    file:close()
  end
end

local function retrieve_token(conf)
  log_msg("--- RUNNING RETRIEVE TOKEN ---")

  -- Check URI params for token (if enabled in conf)
  local uri_params = ngx.req.get_uri_args()
  for _, v in ipairs(conf.uri_param_names or {}) do
    if uri_params[v] then
      return uri_params[v]
    end
  end

  -- Check cookies for token (if enabled in conf)
  local ngx_var = ngx.var
  for _, v in ipairs(conf.cookie_names or {}) do
    local jwt_cookie = ngx_var["cookie_" .. v]
    if jwt_cookie and jwt_cookie ~= "" then
      return jwt_cookie
    end
  end

  -- Check Authorization header for Bearer token
  local auth_header = ngx.req.get_headers()["authorization"]
  if auth_header then
    local iterator, iter_err = ngx_re_gmatch(auth_header, "\\s*[Bb]earer\\s+(.+)")
    if not iterator then
      return nil, iter_err
    end

    local m, err = iterator()
    if err then
      return nil, err
    end

    if m and #m > 0 then
      return m[1]
    end
  end

  return nil, "No authentication token found"
end

local function append_uri(token)
  log_msg("--- FUNCTION APPEND_URI ---")
  
  -- Preserve original URI and append token (matches your requirement)
  local current_uri = ngx.var.uri:gsub("/$", "") -- Remove trailing slash if present
  local new_uri = current_uri .. "/" .. token
  ngx.req.set_uri(new_uri)
  log_msg("Updated request URI to: " .. new_uri)
end

-- Expose public functions for the main plugin to call
local _M = {}

function _M.do_authentication(conf)
  log_msg("--- RUNNING DO_AUTHENTICATION ---")
  
  local token, err = retrieve_token(conf)
  if err then
    return false, {status = 500, message = err}
  end

  local token_type = type(token)
  if token_type ~= "string" then
    if token_type == "nil" then
      return false, {status = 401, message = "Missing Bearer token"}
    elseif token_type == "table" then
      return false, {status = 401, message = "Multiple authentication tokens provided"}
    else
      return false, {status = 401, message = "Unrecognizable authentication token"}
    end
  end

  -- Token is valid, modify the URI
  append_uri(token)
  return true
end

return _M

Additional Recommendations

  1. Use Kong's Native Logging: Replace manual file writes with ngx.log(ngx.INFO, "your message")—this integrates with Kong's existing logging system and avoids file handle leaks.
  2. Verify Plugin Loading: After updating code, restart Kong and run kong plugins list to confirm your ctk plugin is registered.
  3. Adjust Priority: Ensure CtkHandler.PRIORITY = 3505 makes sense for your use case—higher values mean the plugin runs earlier in the request lifecycle.
  4. Test with Debug Logs: Add ngx.log(ngx.ERR, "Access phase triggered") at the start of the access method to quickly confirm it's executing.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:36:42