Skip to content
Hands-on IT IT Drills

Day 11: A Custom Plugin in Lua

Goal: Write your own plugin that passes the name from a verified JWT to the backend as a header, integrate it into Kong, configure it and secure it against forged headers. · Duration: approx. 75 min · Prerequisite: Day 10

Briefing

  • A plugin consists of at least two Lua files: schema.lua describes the configuration, handler.lua contains the logic for the phases of a request.
  • The PRIORITY in the handler determines when it runs. jwt-identity runs at 1400, after jwt (1450): it only sees tokens that have already been verified.
  • The PDK (kong.request, kong.service.request, kong.client, kong.log) is the stable interface to Kong.
  • Kong loads custom plugins via KONG_PLUGINS and the Lua search path.
 Bearer JWT ─► jwt (1450): signature ok, Consumer keycloak
            ─► jwt-identity (1400): X-User = preferred_username from the token
            ─► acl (950) ─► backend sees X-User: anna

Drill 1: The Anatomy

source ~/kong-lab/setup/env.sh
mkdir -p ~/kong-lab/tag11
cp -R ~/kong-lab/code/plugins ~/kong-lab/plugins
cd ~/kong-lab/plugins/kong/plugins/jwt-identity
ls
grep -v '^--' schema.lua

Expected:

handler.lua  schema.lua
local typedefs = require "kong.db.schema.typedefs"

return {
  name = "jwt-identity",
  fields = {
    { consumer = typedefs.no_consumer },
    { protocols = typedefs.protocols_http },
    { config = {
        type = "record",
        fields = {
          { claim = { type = "string", required = true,
                      default = "preferred_username" } },
          { header = { type = "string", required = true, default = "X-User",
                       match = "^X%-[%w%-]+$" } },
        },
    } },
  },
}

Two settings: which claim (claim) goes into which header (header). match is a Lua pattern: the header must start with X-. no_consumer forbids attaching the plugin to a consumer.

sed -n '/^function/,/^end/p' handler.lua

Expected:

function JwtIdentity:access(conf)
  -- Ein vom Client mitgeschickter Header wird immer entfernt.
  kong.service.request.clear_header(conf.header)

  -- Nur wenn die Anmeldung über ein JWT lief, ist das Token geprüft.
  local credential = kong.client.get_credential()
  if not credential or not credential.algorithm then
    return
  end

  local auth = kong.request.get_header("authorization") or ""
  local token = auth:match("^[Bb]earer%s+(.+)$")
  if not token then
    return
  end

  local jwt, err = jwt_parser:new(token)
  if not jwt then
    kong.log.warn("Token nicht lesbar: ", err)
    return
  end

  local value = jwt.claims[conf.claim]
  if type(value) == "string" then
    kong.service.request.set_header(conf.header, value)
    kong.log.info(conf.header, ": ", value)
  end
end

The access phase runs before forwarding. The code contains three rules: always delete a header the client sent along, act only on a JWT login (only JWT credentials have algorithm), and read the token with Kong’s own parser instead of taking Base64 apart yourself.

Save your progress? Sign up for free

Drill 2: Integrate It

cd ~/kong-lab/kong
cp ~/kong-lab/code/tag11/compose.yaml compose.yaml
grep -E 'KONG_PLUGINS|LUA_PACKAGE|kong-plugins' compose.yaml
docker compose up -d --wait
curl -s $ADMIN | jq -c '.plugins.available_on_server["jwt-identity"]'

Expected (shortened):

      KONG_PLUGINS: bundled,jwt-identity
      KONG_LUA_PACKAGE_PATH: /kong-plugins/?.lua;;
      - ../plugins:/kong-plugins:ro   # eigene Plugins (Tag 11)
 Container kong-kong-1 Healthy
{"priority":1400,"version":"0.1.0"}

bundled stands for the 45 bundled plugins. The search path /kong-plugins/?.lua turns kong.plugins.jwt-identity.handler into the file /kong-plugins/kong/plugins/jwt-identity/handler.lua; ;; appends the default path.

Save your progress? Sign up for free

Drill 3: The Schema Validates Too

Kong validates every configuration against your schema before storing it:

curl -s -X POST $ADMIN/schemas/plugins/validate -H 'Content-Type: application/json' \
  -d '{"name":"jwt-identity","config":{"header":"User"}}' | jq -r .message
curl -s -X POST $ADMIN/schemas/plugins/validate -H 'Content-Type: application/json' \
  -d '{"name":"jwt-identity","config":{}}' | jq -r .message

Expected:

schema violation (config.header: invalid value: User)
schema validation successful

Without any values, the defaults from the schema apply.

Save your progress? Sign up for free

Drill 4: On the whoami Service

cd ~/kong-lab/tag11
deck file add-plugins -s ~/kong-lab/kong/kong.yaml \
  --selector '$.services[?(@.name=="whoami")]' \
  --config '{"name":"jwt-identity"}' -o ~/kong-lab/kong/kong.yaml
ksync 2>/dev/null | tail -3
anna_token() {
  curl -s -d grant_type=password -d client_id=notes-cli \
    -d client_secret=lab-client-secret-123 \
    -d username=anna -d password=lab-user-pw-123 \
    $KC/protocol/openid-connect/token | jq -r .access_token
}
T=$(token); U=$(anna_token)
for t in "$T" "$U"; do
  curl -s -H "Authorization: Bearer $t" $PROXY/whoami \
    | jq -c '.headers | {"X-User", "X-Consumer-Username"}'
done

Expected:

  Created: 1
  Updated: 0
  Deleted: 0
{"X-User":["service-account-notes-cli"],"X-Consumer-Username":["keycloak"]}
{"X-User":["anna"],"X-Consumer-Username":["keycloak"]}

The outcome of the Day 6 challenge, now solved: the consumer remains the issuer, but the backend learns who is in the token.

Save your progress? Sign up for free

Drill 5: Forging Is Pointless

Can a client give itself a name?

curl -s -H 'apikey: lab-key-anna-456' -H 'X-User: chef' $PROXY/whoami \
  | jq -c '.headers | {"X-User", "X-Consumer-Username"}'
curl -s -H "Authorization: Bearer $U" -H 'X-User: chef' $PROXY/whoami \
  | jq -c '.headers."X-User"'

Expected:

{"X-User":null,"X-Consumer-Username":["anna"]}
["anna"]

With a key, X-User stays empty: the plugin deletes the header and does not set a new one, because the login did not go through a JWT. With a token, the name from the token wins. Without the first line in access, any client could send X-User: chef, and a backend that trusts the header would be wide open.

Save your progress? Sign up for free

Drill 6: Configure It Differently

The same plugin, a different claim:

P='$.services[?(@.name=="whoami")].plugins[?(@.name=="jwt-identity")]'
deck file patch -s ~/kong-lab/kong/kong.yaml --selector "$P" \
  --value 'config:{"claim":"email","header":"X-User-Email"}' -o mail.yaml
deck gateway sync mail.yaml 2>/dev/null | tail -2; sleep 5
curl -s -H "Authorization: Bearer $(anna_token)" $PROXY/whoami \
  | jq -c '.headers | {"X-User", "X-User-Email"}'
ksync 2>/dev/null | tail -1

Expected:

  Updated: 1
  Deleted: 0
{"X-User":null,"X-User-Email":["[email protected]"]}
  Deleted: 0

The plugin was created without config in Drill 4, which is why the patch replaces the whole config field. ksync then restores the state from kong.yaml.

Save your progress? Sign up for free

Drill 7: Change the Code and Read the Logs

The handler writes with kong.log.info. None of it shows up in the log:

curl -s -o /dev/null -H "Authorization: Bearer $(anna_token)" $PROXY/whoami
docker compose -f ~/kong-lab/kong/compose.yaml logs kong 2>&1 \
  | grep -c 'jwt-identity.*X-User'
curl -s $ADMIN | jq -r .configuration.log_level

Expected:

0
notice

Kong logs from notice upward. Change the line in the code. New code does not need ksync, but a restart of the workers:

H=~/kong-lab/plugins/kong/plugins/jwt-identity/handler.lua
ALT='kong.log.info(conf.header, ": ",'
NEU='kong.log.notice("gesetzt: ", conf.header, "=",'
sed -i "s/$ALT/$NEU/" $H
docker compose -f ~/kong-lab/kong/compose.yaml exec kong kong reload; sleep 5
curl -s -o /dev/null -H "Authorization: Bearer $(anna_token)" $PROXY/whoami
docker compose -f ~/kong-lab/kong/compose.yaml logs kong 2>&1 \
  | grep -o '\[jwt-identity\] gesetzt: [^,]*' | tail -1

Expected:

Kong reloaded
[jwt-identity] gesetzt: X-User=anna

Kong prefixes every line with the plugin’s name. In production, set KONG_LOG_LEVEL to info or debug only for troubleshooting, because it then also logs request contents.

Save the state:

cd ~/kong-lab/kong
git add compose.yaml kong.yaml && git commit -qm "Tag 11: Plugin jwt-identity"

Save your progress? Sign up for free

Checkpoint

curl -s $ADMIN/plugins | jq -r '.data[] | select(.name == "jwt-identity")
  | [.name, .config.claim, .config.header] | @tsv'

Expected: one instance with the default values.

jwt-identity    preferred_username  X-User
curl -s -H "Authorization: Bearer $(token)" $PROXY/whoami | jq -r '.headers."X-User"[0]'

Expected: the name from the token.

service-account-notes-cli
curl -s -H 'apikey: lab-key-anna-456' -H 'X-User: chef' $PROXY/whoami \
  | jq -c '.headers."X-User"'

Expected: no header; the forgery is gone.

null

Challenge

An attacker builds a token without a signature with preferred_username: chef and sends it to a route that has jwt-identity but no jwt. What arrives at the backend? Try it on the echo route.

Note: Attach the plugin to the echo service with --config; a token without a signature is header and payload in Base64url with a dot at the end.

Solution

cd ~/kong-lab/tag11
deck file add-plugins -s ~/kong-lab/kong/kong.yaml \
  --selector '$.services[?(@.name=="echo")]' \
  --config '{"name":"jwt-identity"}' -o echo.yaml
deck gateway sync echo.yaml 2>/dev/null | tail -2; sleep 5
b64() { base64 -w0 | tr '/+' '_-' | tr -d '='; }
KOPF=$(echo -n '{"alg":"none"}' | b64)
INHALT=$(echo -n '{"preferred_username":"chef"}' | b64)
FAKE="$KOPF.$INHALT."
curl -s -H "Authorization: Bearer $FAKE" -H 'X-User: chef' $PROXY/echo/headers \
  | jq -c '.headers."X-User"'
ksync 2>/dev/null | tail -1

Expected:

  Updated: 0
  Deleted: 0
null
  Deleted: 1

Nothing. Without jwt there is no JWT credential, so the plugin sets no name and deletes the one that was sent along. That is exactly why it checks credential.algorithm instead of trusting a token that is merely readable.

Save your progress? Sign up for free

Enterprise Note

  • Testing with Pongo: Kong’s tool pongo starts Kong and Postgres in containers and runs unit and integration tests (busted) for custom plugins.
  • Shipping: As a LuaRocks package or copied into your own image; a mounted directory in the container as here is for the lab only.
  • Other languages: Kong has PDKs for Go, Python and JavaScript; these plugins run as separate processes and are slower than Lua.
  • Konnect and Enterprise load custom plugins into the control plane via schemas; the code still has to be present on every data plane node (Day 13).