To insert a field from the request body directly into the header so you can rate limit on a specific field in Kong Gateway, use the Pre-Function plugin together with the Kong Plugin Development Kit (PDK). This approach lets you manipulate the request before it reaches the upstream service, so you can extract the desired field from the request body and insert it into the request header.
Here is a practical example of how you can accomplish this task:
-
Use the following Lua script as a template for your Pre-Function plugin configuration. This script extracts the
numberfield from a JSON object in the request body and adds it as a custom header (x-contact-number) to the request:-- Example request body -- {"contacts": [{"phoneNumber": {"number": "123456789"}}]} local rl_header_name = kong.request.get_body() if (rl_header_name.contacts and #rl_header_name.contacts == 1) then if (rl_header_name.contacts[1].phoneNumber and rl_header_name.contacts[1].phoneNumber.number) then kong.service.request.add_header("x-contact-number", rl_header_name.contacts[1].phoneNumber.number) end end -
Add this Lua script to the
config.accessparameter of the Pre-Function plugin configuration. This step is crucial, as it tells Kong Gateway to execute your custom logic during the access phase of the request processing. -
Apply the plugin configuration to your required scope. See the Pre-Function plugin config examples for guidance.
-
Once the Pre-Function plugin is correctly configured with this script, Kong Gateway will automatically insert the
numberfield from the request body into the request header asx-contact-number. You can then set up rate limiting based on this header as per your requirements.
This method provides a flexible way to manipulate request headers based on the content of the request body, enabling more granular control over rate limiting and other policies in Kong Gateway.