Event Hooks Examples
Event hooks are outbound calls from Kong Gateway. With event hooks, the Kong Gateway can communicate with target services or resources, letting the target know that an event was triggered. When an event is triggered in Kong, it calls a URL with information about that event. Event hooks add a layer of configuration for subscribing to worker events using the admin interface. Worker events are integrated into Kong Gateway to communicate within the gateway context. For example, when an entity is created, the Kong Gateway fires an event with information about the entity. Parts of the Kong Gateway codebase can subscribe to these events, then process the events using callbacks.
In Kong Gateway, these callbacks can be defined using one fo the following “handlers”:
webhook: Makes a JSON POST request to a provided URL with the event data as a payload. Useful for building a middle tier integration (your own webhook that receives Kong hooks). Specific headers can be configured for the request.
webhook-custom: Fully configurable request. Useful for building a direct integration with a service (for example, a Slack webhook). Because it’s fully configurable, it’s more complex to configure. It supports templating on a configurable body, a configurable form payload, and headers.
log: This handler, which requires no configuration, logs the event and the content of the payload into the Kong Gateway logs. If using hybrid mode, the
crud
anddao:crud
sources will log on the control plane logs and thebalancer
andrate-limiting-advanced
sources will log on the data plane logs.lambda: This handler runs specified Lua code after an event is triggered.
Webhook
Webhook event hooks make JSON POST requests to a provided URL with the event data as a payload. For this example, we will use a site that is helpful for testing webhooks: https://webhook.site.
To create a webhook event hook:
- Generate a URL by navigating to https://webhook.site in your web browser.
- Select Copy to clipboard next to Your unique URL.
Create a webhook event hook on the
consumers
event (Kong entity the event hook will listen to for events), on thecrud
source (action that triggers logging), and the URL you copied from step 2 using the following HTTP request:cURL
HTTPie
curl -i -X POST http://{HOSTNAME}:8001/event-hooks \
-d source=crud \
-d event=consumers \
-d handler=webhook \
-d config.url={WEBHOOK_URL}
http -f :8001/event-hooks \
source=crud \
event=consumers \
handler=webhook \
config.url={WEBHOOK_URL}
Navigate to the URL from step 2. You should see a POST request, of type
ping
, notifying our webhook endpoint about the creation of this webhook.In Kong Manager or Kong Admin API, add a consumer from any workspace.
Kong Manager
Admin API
- Select the workspace.
- Select Consumers in the left navigation.
- Select the New Consumer button.
- Enter a Username.
- (Optional) Enter a Custom ID and any Tags.
- Select the Create button.
Create a consumer, Ada Lovelace, by making the following HTTP request to your instance of the Kong Admin API:
cURL
HTTPie
curl -i -X POST http://{HOSTNAME}:8001/consumers \
-d username="Ada Lovelace"
http -f :8001/consumers \
username="Ada Lovelace"
Check the URL from the https://webhook.site page. You should see an entry with data for the new consumer in its payload.
{
"source": "crud",
"entity": {
"created_at": 1627581878,
"type": 0,
"username": "Ada Lovelace",
"id": "0fd2319f-13ea-4582-a448-8d11893026a8"
},
"event": "consumers",
"operation": "create",
"schema": "consumers"
}
Custom webhook
Custom webhook event hooks are fully customizable requests. Custom webhooks are useful for building direct integration with a service. Because custom webhooks are fully configurable, they have more complex configurations. Custom webhooks support Lua templating on a configurable body, form payload, and headers. For a list of possible fields for templating, see the sources endpoint.
The following example sends a message to Slack any time a new administrator is invited to Kong Gateway. Slack allows for incoming webhooks and we can use these to build an integration with Kong’s event hooks features.
To create a custom webhook event hook:
- Create an app in Slack.
- Activate incoming webhooks in the settings for your new app.
- Select to Add New Webhook to Workspace, select the channel where you wish to receive notices, and select Allow.
- Copy the Webhook URL, for example
https://hooks.slack.com/services/foo/bar/baz
. Create a webhook event hook on the
admins
event (Kong entity the event hook will listen to for events), and thecrud
source (action that triggers logging), and format the payload as, “Admin account `{{ entity.username }}` {{ operation }}d; e-mail address set to `{{ entity.email }}`”, using the following HTTP request:cURL
HTTPie
curl -i -X POST http://{HOSTNAME}:8001/event-hooks \
-d source=crud \
-d event=admins \
-d handler=webhook-custom \
-d config.method=POST \
-d config.url={WEBHOOK_URL} \
-d config.headers.content-type="application/json" \
-d config.payload.text="Admin account \`{{ entity.username }}\` {{ operation}}d; email address set to \`{{ entity.email }}\`"
http -f :8001/event-hooks \
source=crud \
event=admins \
handler=webhook-custom \
config.method=POST \
config.url={WEBHOOK_URL} \
config.headers.content-type="application/json" \
config.payload.text="Admin account \`{{ entity.username }}\` {{ operation}}d; email address set to \`{{ entity.email }}\`"
Turn on RBAC.
To enable RBAC, you will need the initial KONG_PASSWORD that was used when you first installed Kong Gateway and ran migrations. This is also the default password for the Super Admin, and will be required once RBAC is on.
UNIX-based system or Windows
Docker
Modify configuration settings below in your
kong.conf
file. Navigate to the file at/etc/kong/kong.conf
:cd /etc/kong/
Copy the
kong.conf.default
file so you know you have a working copy to fall back to.cp kong.conf.default kong.conf
Now, edit the following settings in
kong.conf
:echo >> “enforce_rbac = on” >> /etc/kong/kong.confecho >> “admin_gui_auth = basic-auth” >> /etc/kong.confecho >> “admin_gui_session_conf = {"secret":"secret","storage":"kong","cookie_secure":false}”
This will turn on RBAC, tell Kong Gateway to use basic authentication (username/password), and tell the Sessions Plugin how to create a session cookie.
The cookie is used for all subsequent requests to authenticate the user until it expires. The session has a limited duration and renews at a configurable interval, which helps prevent an attacker from obtaining and using a stale cookie after the session has ended.
Restart Kong Gateway and point to the new config file:
kong restart -c /etc/kong/kong.conf
If you have a Docker installation, run the following command to set the needed environment variables and reload the gateway’s configuration.
Note: make sure to replace
<kong-container-id>
with the ID of your container.echo "KONG_ENFORCE_RBAC=on
KONG_ADMIN_GUI_AUTH=basic-auth
KONG_ADMIN_GUI_SESSION_CONF='{\"secret\":\"secret\",\"storage\":\"kong\",\"cookie_secure\":false}'
kong reload exit" | docker exec -i {KONG_CONTAINER_ID} /bin/sh
This will turn on RBAC, tell Kong Gateway to use basic authentication (username/password), and tell the Sessions Plugin how to create a session cookie.
The cookie is used for all subsequent requests to authenticate the user, until it expires. The session has a limited duration and renews at a configurable interval, which helps prevent an attacker from obtaining and using a stale cookie after the session has ended.
Outside of this guide, you will likely want to modify these settings differently, depending on your installation. You can read more about these settings here: Basic Auth for Kong Manager.
Invite an Admin using Kong Manager or the Kong Admin API.
Kong Manager
Admin API
- Go to Kong Manager, or reload the page if you already have it open and you will see a login screen.
- Log in to Kong Manager with the built-in Super Admin account,
kong_admin
, and its password. This is the initialKONG_PASSWORD
you used when you ran migrations during installation. - From the Teams > Admins tab, click Invite Admin.
- Enter the new administrator’s Email address and Username.
- Click Invite Admin to send the invite. At this point in the getting started guide, you likely haven’t set up SMTP yet, so no email will be sent.
Create an admin, Arya Stark, by making the following HTTP request to your instance of the Kong Admin API:
Note: Replace
{KONG_ADMIN_PASSWORD
} with yourkong_admin
password. This is the initialKONG_PASSWORD
you used when you ran migrations during installation.cURL
HTTPie
curl -i -X POST http://{HOSTNAME}:8001/admins \
-d username="Arya Stark" \
-d email=arya@gameofthrones.com \
-H Kong-Admin-Token:{KONG_ADMIN_PASSWORD}
http -f :8001/admins \
username="Arya Stark" \
email=arya@gameofthrones.com \
Kong-Admin-Token={KONG_ADMIN_PASSWORD}
Afterwards, you should receive a message in the Slack channel you selected with the message you included as the config.payload.text
.
Log
Log event hooks log the specified event and content of the payload into the Kong Gateway logs.
To create a log event hook:
Create a log event hook on the
consumers
event (Kong entity the event hook will listen to for events) and on thecrud
source (action that triggers logging) using the following HTTP request:cURL
HTTPie
curl -i -X POST http://{HOSTNAME}:8001/event-hooks \
-d source=crud \
-d event=consumers \
-d handler=log
http -f :8001/event-hooks \
source=crud \
event=consumers \
handler=log
In Kong Manager or Kong Admin API, add a consumer from any workspace.
Kong Manager
Admin API
- Select the workspace.
- Select Consumers in the left navigation.
- Select the New Consumer button.
- Enter a Username.
- (Optional) Enter a Custom ID and any Tags.
- Select the Create button.
Create a consumer, Elizabeth Bennet, by making the following HTTP request to your instance of the Kong Admin API:
cURL
HTTPie
curl -i -X POST http://{HOSTNAME}:8001/consumers \
-d username="Elizabeth Bennet"
http -f :8001/consumers \
username="Elizabeth Bennet"
You should see an entry with data for the new consumer in the payload in Kong’s error log, which is typically accessible at
/usr/local/kong/logs/error.log
.172.19.0.1 - - [29/Jul/2021:15:57:15 +0000] "POST /consumers HTTP/1.1" 409 147 "-" "HTTPie/2.4.0"
2021/07/29 15:57:26 [notice] 68854#0: *819021 +--------------------------------------------------+, context: ngx.timer, client: 172.19.0.1, server: 0.0.0.0:8001
2021/07/29 15:57:26 [notice] 68854#0: *819021 |[kong] event_hooks.lua:?:452 "log callback: " { "consumers", "crud", {|, context: ngx.timer, client: 172.19.0.1, server: 0.0.0.0:8001
2021/07/29 15:57:26 [notice] 68854#0: *819021 | entity = { |, context: ngx.timer, client: 172.19.0.1, server: 0.0.0.0:8001
2021/07/29 15:57:26 [notice] 68854#0: *819021 | created_at = 1627574246, |, context: ngx.timer, client: 172.19.0.1, server: 0.0.0.0:8001
2021/07/29 15:57:26 [notice] 68854#0: *819021 | id = "4757bd6b-8d54-4b08-bf24-01e346a9323e",|, context: ngx.timer, client: 172.19.0.1, server: 0.0.0.0:8001
2021/07/29 15:57:26 [notice] 68854#0: *819021 | type = 0, |, context: ngx.timer, client: 172.19.0.1, server: 0.0.0.0:8001
2021/07/29 15:57:26 [notice] 68854#0: *819021 | username = "Elizabeth Bennet" |, context: ngx.timer, client: 172.19.0.1, server: 0.0.0.0:8001
2021/07/29 15:57:26 [notice] 68854#0: *819021 | }, |, context: ngx.timer, client: 172.19.0.1, server: 0.0.0.0:8001
2021/07/29 15:57:26 [notice] 68854#0: *819021 | operation = "create", |, context: ngx.timer, client: 172.19.0.1, server: 0.0.0.0:8001
2021/07/29 15:57:26 [notice] 68854#0: *819021 | schema = "consumers" |, context: ngx.timer, client: 172.19.0.1, server: 0.0.0.0:8001
2021/07/29 15:57:26 [notice] 68854#0: *819021 | }, 68854 } |, context: ngx.timer, client: 172.19.0.1, server: 0.0.0.0:8001
2021/07/29 15:57:26 [notice] 68854#0: *819021 +--------------------------------------------------+, context: ngx.timer, client: 172.19.0.1, server: 0.0.0.0:8001
Lambda
The lambda event hook allows you to write completely custom logic in Lua code and hook it into a variety of Kong events. The following example writes a log entry any time a consumer changes, but conditionally and with custom formatting.
To create a lambda event hook:
Create a Lua script to load into the lambda event hook and save it to a file named
lambda.lua
on your home directory.return function (data, event, source, pid)
local user = data.entity.username
error("Event hook on consumer " .. user .. "")
end
Create a lambda event hook on the
consumers
event (Kong entity the event hook will listen to for events) and on thecrud
source (action that triggers logging) using the following HTTP request:cURL
HTTPie
curl -i -X POST http://{HOSTNAME}:8001/event-hooks \
-d source=crud \
-d event=consumers \
-d handler=lambda \
-F config.functions='return function (data, event, source, pid) local user = data.entity.username error("Event hook on consumer " .. user .. "")end'
http -f :8001/event-hooks \
source=crud \
event=consumers \
handler=lambda \
config.functions[]=@~/lambda.lua
In Kong Manager or Kong Admin API, add a consumer to any workspace.
Kong Manager
Admin API
- Select the workspace.
- Select Consumers in the left navigation.
- Select the New Consumer button.
- Enter a Username.
- (Optional) Enter a Custom ID and any Tags.
- Select the Create button.
Create a consumer, Lois Lane, by making the following HTTP request to your instance of the Kong Admin API:
cURL
HTTPie
curl -i -X POST http://{HOSTNAME}:8001/consumers \
-d username="Lois Lane"
http -f :8001/consumers \
username="Lois Lane"
You should see an entry “Event hook on consumer Lois Lane” in Kong’s error log, which is typically accessible at
/usr/local/kong/logs/error.log
.2021/07/29 21:52:54 [error] 114#0: *153047 [kong] event_hooks.lua:190 [string "return function (data, event, source, pid)..."]:3: Event hook on consumer Lois Lane, context: ngx.timer, client: 172.19.0.1, server: 0.0.0.0:8001