Accessing authenticated_consumer in custom plugin

Hi,

I am looking for some advice on how to correctly access the ngx.ctx.authenticated_consumer in a plugin. I have a custom plugin that can read the properties of the authenticated_consumer and add it to the request body (along the same lines as the request-transformer plugin).

The plugin includes an access.lua module, similar to the request-transformer plugin.

local _M = {}
local consumer = nil

function _M.execute()
    consumer = ngx.ctx.authenticated_consumer
    return consumer.username
end

return _M

In handler.lua

local BasePlugin = require "kong.plugins.base_plugin"
local my_plugin_access= require "myplugin.access"
local MyPlugin = BasePlugin:extend()

function MyPlugin:new()
  MyPlugin.super.new(self, "my-plugin")
end

function MyPlugin:access(conf)
  MyPlugin.super.access(self)
  local username = my_plugin_access.execute()
  ngx.log(ngx.NOTICE, string.format("consumer username is %s", username))
end

MyPlugin.PRIORITY = 802
MyPlugin.VERSION = "0.1.0"

return MyPlugin

When the plugin is run for multiple requests I am finding that the value of username in some cases is not the username of the authenticated_consumer of the current request but is the username of another request executing at the same time.

I suspect I have not fully understood scoping in Lua and the consumer variable in access.lua is like a static variable and its value is being overwritten when the plugin is being executed by multiple requests.

And advice on how I should correctly access ngx.ctx.authenticated_consumer to get the correct username for each request will be much appreciated.

Thanks.

Hi,

I’m not sure which authentication plugin you are using, or whether this really is the entirety of your plugin? Authentication plugins should always provide ngx.ctx.authenticated_consumer once a request is authenticated (and short-circuit it if not).

From what I can see, with the default set of authentication plugins provided by Kong, this should always run later than those (considering the PRIORITY you chose). That said, I see little benefit for scoping the consumer variable at the top level of your module, even though it should result in the same behavior.