Filter requests based on header names
You can use the serverless Pre-Function plugin to detect headers in a request, and either let the request through or terminate it.
In this tutorial, we’ll enable the Pre-Function plugin in the access
phase, where it will look for a request with the header X-Custom-Auth
.
If the header exists in the request, it lets the request through. If the header doesn’t exist, it terminates the request early.
Prerequisites
Kong Konnect
This is a Konnect tutorial and requires a Konnect personal access token.
-
Create a new personal access token by opening the Konnect PAT page and selecting Generate Token.
-
Export your token to an environment variable:
export KONNECT_TOKEN='YOUR_KONNECT_PAT'
Copied to clipboard! -
Run the quickstart script to automatically provision a Control Plane and Data Plane, and configure your environment:
curl -Ls https://get.konghq.com/quickstart | bash -s -- -k $KONNECT_TOKEN --deck-output
Copied to clipboard!This sets up a Konnect Control Plane named
quickstart
, provisions a local Data Plane, and prints out the following environment variable exports:export DECK_KONNECT_TOKEN=$KONNECT_TOKEN export DECK_KONNECT_CONTROL_PLANE_NAME=quickstart export KONNECT_CONTROL_PLANE_URL=https://us.api.konghq.com export KONNECT_PROXY_URL='http://localhost:8000'
Copied to clipboard!Copy and paste these into your terminal to configure your session.
Enable the Pre-Function plugin
The Pre-Function plugin lets you execute Lua code that runs before other plugins in a particular phase. In this case, we’re using the plugin to look for a specific header, x-custom-auth
.
The following example applies the Pre-Function plugin globally, in the access phase:
echo '
_format_version: "3.0"
plugins:
- name: pre-function
config:
access:
- |
-- Get list of request headers
local custom_auth = kong.request.get_header("x-custom-auth")
-- Terminate request early if the custom authentication header
-- does not exist
if not custom_auth then
return kong.response.exit(401, "Invalid Credentials")
end
' | deck gateway apply -
Validate
Let’s test that the code will terminate the request when no header is passed:
curl -i "$KONNECT_PROXY_URL/anything"
curl -i "http://localhost:8000/anything"
You should get a 401
status code with the message Invalid Credentials
.
Now, test the code by making a valid request with the x-custom-auth
header:
curl -i "$KONNECT_PROXY_URL/anything" \
-H "x-custom-auth: example"
curl -i "http://localhost:8000/anything" \
-H "x-custom-auth: example"
This time, the request will pass through and you’ll see a 200
response.
Cleanup
Clean up Konnect environment
If you created a new control plane and want to conserve your free trial credits or avoid unnecessary charges, delete the new control plane used in this tutorial.