Skip to content
Kong Logo | Kong Docs Logo
search
  • We're Hiring!
  • Docs
    • Kong Gateway
    • Kong Konnect
    • Kong Mesh
    • Plugin Hub
    • decK
    • Kubernetes Ingress Controller
    • Insomnia
    • Kuma

    • Docs contribution guidelines
  • Plugin Hub
  • Support
  • Community
  • Kong Academy
Get a Demo Start Free Trial
  • Kong Gateway
  • Kong Konnect
  • Kong Mesh
  • Plugin Hub
  • decK
  • Kubernetes Ingress Controller
  • Insomnia
  • Kuma

  • Docs contribution guidelines
  • 3.2.x (latest)
  • 3.1.x
  • 3.0.x
  • 2.8.x
  • 2.7.x
  • 2.6.x
  • Older Enterprise versions (2.1-2.5)
  • Older OSS versions (2.1-2.5)
  • Archive (pre-2.1)
    • Overview of Kong Gateway
      • Version Support Policy
      • Third Party Dependencies
      • Browser Support
    • Stability
    • Release Notes
      • Services
        • Overview
        • Configure Routes with Expressions
      • Upstreams
      • Plugins
      • Routing Traffic
      • Load Balancing
      • Health Checks and Circuit Breakers
      • Kong Performance Testing
    • Glossary
    • Get Kong
    • Services and Routes
    • Rate Limiting
    • Proxy Caching
    • Key Authentication
    • Load-Balancing
      • Overview
        • Overview
        • Deploy Kong Gateway in Hybrid mode
      • DB-less Deployment
      • Traditional
      • Overview
        • Helm
        • OpenShift with Helm
        • kubectl apply
        • Kubernetes Deployment Options
        • Using docker run
        • Build your own Docker images
        • Amazon Linux
        • Debian
        • Red Hat
        • Ubuntu
      • Running Kong as a non-root user
      • Securing the Admin API
      • Using systemd
      • Start Kong Gateway Securely
      • Programatically Creating Admins
      • Enabling RBAC
      • Overview
      • Download your License
      • Deploy Enterprise License
      • Using the License API
      • Monitor Licenses Usage
      • Default Ports
      • DNS Considerations
      • Network and Firewall
      • CP/DP Communication through a Forward Proxy
        • Configure PostgreSQL TLS
        • Troubleshooting PostgreSQL TLS
    • Kong Configuration File
    • Environment Variables
    • Serving a Website and APIs from Kong
      • Overview
      • Prometheus
      • StatsD
      • Datadog
      • Overview
      • Writing a Custom Trace Exporter
      • Tracing API Reference
    • Resource Sizing Guidelines
    • Security Update Process
    • Blue-Green Deployments
    • Canary Deployments
    • Clustering Reference
      • Log Reference
      • Dynamic log level updates
      • Customize Gateway Logs
      • Upgrade Kong Gateway 3.x.x
      • Migrate from OSS to Enterprise
    • Overview
      • Overview
      • Metrics
      • Analytics with InfluxDB
      • Analytics with Prometheus
      • Estimate Analytics Storage in PostgreSQL
      • Overview
      • Getting Started
      • Advanced Usage
        • Overview
        • Environment Variables
        • AWS Secrets Manager
        • Google Secrets Manager
        • Hashicorp Vault
        • Securing the Database with AWS Secrets Manager
      • Reference Format
      • Overview
      • Get Started with Dynamic Plugin Ordering
      • Overview
      • Enable the Dev Portal
      • Publish an OpenAPI Spec
      • Structure and File Types
      • Themes Files
      • Working with Templates
      • Using the Editor
        • Basic Auth
        • Key Auth
        • OIDC
        • Sessions
        • Adding Custom Registration Fields
        • Manage Developers
        • Developer Roles and Content Permissions
        • Authorization Provider Strategy
        • Enable Application Registration
        • Enable Key Authentication for Application Registration
          • External OAuth2 Support
          • Set up Okta and Kong for External Oauth
          • Set up Azure AD and Kong for External Authentication
        • Manage Applications
        • Theme Editing
        • Migrating Templates Between Workspaces
        • Markdown Rendering Module
        • Customizing Portal Emails
        • Adding and Using JavaScript Assets
        • Single Page App in Dev Portal
        • Alternate OpenAPI Renderer
      • SMTP
      • Workspaces
      • Helpers CLI
      • Portal API Documentation
    • Audit Logging
    • Keyring and Data Encryption
    • Workspaces
    • Consumer Groups
    • Event Hooks
    • Configure Data Plane Resilience
    • About Control Plane Outage Management
      • Overview
      • Install the FIPS Compliant Package
      • FIPS 140-2 Compliant Plugins
    • Overview
    • Enable Kong Manager
      • Services and Routes
      • Rate Limiting
      • Proxy Caching
      • Authentication with Consumers
      • Load Balancing
      • Overview
      • Create a Super Admin
      • Workspaces and Teams
      • Reset Passwords and RBAC Tokens
      • Basic Auth
        • Configure LDAP
        • LDAP Service Directory Mapping
        • Configure OIDC
        • OIDC Authenticated Group Mapping
      • Sessions
        • Overview
        • Enable RBAC
        • Add a Role and Permissions
        • Create a User
        • Create an Admin
    • Networking Configuration
    • Workspaces
    • Create Consumer Groups
    • Sending Email
    • Overview
    • File Structure
    • Implementing Custom Logic
    • Plugin Configuration
    • Accessing the Data Store
    • Storing Custom Entities
    • Caching Custom Entities
    • Extending the Admin API
    • Writing Tests
    • (un)Installing your Plugin
      • Overview
      • kong.client
      • kong.client.tls
      • kong.cluster
      • kong.ctx
      • kong.ip
      • kong.jwe
      • kong.log
      • kong.nginx
      • kong.node
      • kong.request
      • kong.response
      • kong.router
      • kong.service
      • kong.service.request
      • kong.service.response
      • kong.table
      • kong.tracing
      • kong.vault
      • kong.websocket.client
      • kong.websocket.upstream
      • Go
      • Javascript
      • Python
      • Running Plugins in Containers
      • External Plugin Performance
    • Overview
        • Overview
        • OpenID Connect with Curity
        • OpenID Connect with Azure AD
        • OpenID Connect with Google
        • OpenID Connect with Okta
        • OpenID Connect with Auth0
        • OpenID Connect with Cognito
      • Authentication Reference
      • Allow Multiple Authentication Plugins
    • Rate Limiting Plugin
      • Add a Body Value
    • GraphQL
      • gRPC Plugins
      • Configure a gRPC service
    • Overview
    • Information Routes
    • Health Routes
    • Tags
    • Debug Routes
    • Services
    • Routes
    • Consumers
    • Plugins
    • Certificates
    • CA Certificates
    • SNIs
    • Upstreams
    • Targets
    • Vaults
    • Keys
    • Licenses
    • Workspaces
    • RBAC
    • Admins
    • Developers
    • Consumer Groups
    • Event Hooks
    • Keyring and Data Encryption
    • Audit Logs
    • kong.conf
    • Injecting Nginx Directives
    • CLI
    • Key Management
    • Performance Testing Framework
    • Router Expressions Language
    • FAQ

github-edit-pageEdit this page

report-issueReport an issue

enterprise-switcher-iconSwitch to OSS

On this page
  • Webhook
  • Custom webhook
  • Log
  • Lambda
Kong Gateway
3.2.x (latest)
  • Home
  • Kong Gateway
  • Kong Enterprise
  • Event Hooks
  • Event Hooks Examples

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 of 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 and dao:crud sources will log on the control plane logs and the balancer and rate-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:

  1. Generate a URL by navigating to https://webhook.site in your web browser.
  2. Select Copy to clipboard next to Your unique URL.
  3. Create a webhook event hook on the consumers event (Kong entity the event hook will listen to for events), on the crud 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}
  4. 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.
  5. In Kong Manager or Kong Admin API, add a consumer from any workspace.

    Kong Manager
    Admin API
    1. Select the workspace.
    2. Select Consumers in the left navigation.
    3. Select the New Consumer button.
    4. Enter a Username.
    5. (Optional) Enter a Custom ID and any Tags.
    6. 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"
  6. 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:

  1. Create an app in Slack.
  2. Activate incoming webhooks in the settings for your new app.
  3. Select to Add New Webhook to Workspace, select the channel where you wish to receive notices, and select Allow.
  4. Copy the Webhook URL, for example https://hooks.slack.com/services/foo/bar/baz.
  5. Create a webhook event hook on the admins event (Kong entity the event hook will listen to for events), and the crud 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 }}\`"
  6. 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
    1. Modify configuration settings below in your kong.conf file. Navigate to the file at /etc/kong/kong.conf:
       cd /etc/kong/
       
    2. Copy the kong.conf.default file so you know you have a working copy to fall back to.
       cp kong.conf.default kong.conf
       
    3. Now, edit the following settings in kong.conf:

       echo >> “enforce_rbac = on” >> /etc/kong/kong.conf
        echo >> “admin_gui_auth = basic-auth” >> /etc/kong.conf
        echo >> “admin_gui_session_conf = {"secret":"secret","storage":"kong","cookie_secure":false}”
       

      This turns on RBAC, tells Kong Gateway to use basic authentication (username/password), and tells 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.

    4. 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 turns RBAC on, tells Kong Gateway to use basic authentication (username/password), and tells 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.

  7. Invite an Admin using Kong Manager or the Kong Admin API.

    Kong Manager
    Admin API
    1. Go to Kong Manager, or reload the page if you already have it open and you will see a login screen.
    2. Log in to Kong Manager with the built-in Super Admin account, kong_admin, and its password. This is the initial KONG_PASSWORD you used when you ran migrations during installation.
    3. From the Teams > Admins tab, click Invite Admin.
    4. Enter the new administrator’s Email address and Username.
    5. 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 your kong_admin password. This is the initial KONG_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:

  1. Create a log event hook on the consumers event (Kong entity the event hook will listen to for events) and on the crud 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
  2. In Kong Manager or Kong Admin API, add a consumer from any workspace.

    Kong Manager
    Admin API
    1. Select the workspace.
    2. Select Consumers in the left navigation.
    3. Select the New Consumer button.
    4. Enter a Username.
    5. (Optional) Enter a Custom ID and any Tags.
    6. 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"
  3. 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.

The lambda event hook type is extremely powerful: you can write completely custom logic to handle any use case you want. However, it’s restricted by default through the sandbox.. This sandbox is put in place to keep users safe: it’s easy to inadvertently add unsafe libraries/objects into the sandbox and leave the Kong Gateway exposed to security vulnerabilities. Use caution before modifying these sandbox settings.

To create a lambda event hook:

  1. 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
    
  2. Create a lambda event hook on the consumers event (Kong entity the event hook will listen to for events) and on the crud 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
  3. In Kong Manager or Kong Admin API, add a consumer to any workspace.

    Kong Manager
    Admin API
    1. Select the workspace.
    2. Select Consumers in the left navigation.
    3. Select the New Consumer button.
    4. Enter a Username.
    5. (Optional) Enter a Custom ID and any Tags.
    6. 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"
  4. 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
    
Thank you for your feedback.
Was this page useful?
  • Kong
    THE CLOUD CONNECTIVITY COMPANY

    Kong powers reliable digital connections across APIs, hybrid and multi-cloud environments.

    • Company
    • Customers
    • Events
    • Investors
    • Careers Hiring!
    • Partners
    • Press
    • Contact
  • Products
    • Kong Konnect
    • Kong Gateway
    • Kong Mesh
    • Get Started
    • Pricing
  • Resources
    • eBooks
    • Webinars
    • Briefs
    • Blog
    • API Gateway
    • Microservices
  • Open Source
    • Install Kong Gateway
    • Kong Community
    • Kubernetes Ingress
    • Kuma
    • Insomnia
  • Solutions
    • Decentralize
    • Secure & Govern
    • Create a Dev Platform
    • API Gateway
    • Kubernetes
    • Service Mesh
Star
  • Terms•Privacy
© Kong Inc. 2023