---
title: "Secure Kong APIs with API Key Authentication"
description: "Secure your Kong API using a shared secret."
canonicalUrl: "https://zuplo.com/use-cases/api-key-auth/lua/kong/secure-header"
framework: "Kong"
language: "Lua"
authStrategy: "shared secret header"
pageType: use-case
---

# Secure Kong APIs with API Key Authentication

Secure your Kong API using a shared secret.

## How Zuplo Handles It

Put Zuplo in front of your Kong backend to authenticate API keys and forward a shared secret header so your origin only accepts traffic from Zuplo.

## Kong Backend Code

```lua
-- Handler to validate shared secret
local BasePlugin = require "kong.plugins.base_plugin"
local responses = require "kong.tools.responses"
local ngx = ngx
local kong = kong

local SharedSecretHandler = BasePlugin:extend()

function SharedSecretHandler:new()
  SharedSecretHandler.super.new(self, "shared-secret")
end

function SharedSecretHandler:access(conf)
  SharedSecretHandler.super.access(self)

  local secret = ngx.req.get_headers()["x-shared-secret"]
  local expected_secret = os.getenv("SHARED_SECRET")

  if not expected_secret then
    return responses.send_HTTP_INTERNAL_SERVER_ERROR("Server configuration error")
  end

  if not secret then
    return responses.send_HTTP_UNAUTHORIZED("No secret provided")
  end

  -- Timing-safe comparison to prevent timing attacks
  if #secret ~= #expected_secret or secret ~= expected_secret then
    return responses.send_HTTP_UNAUTHORIZED("Invalid secret")
  end
end

-- Create the plugin schema
SharedSecretHandler.PRIORITY = 1000
SharedSecretHandler.VERSION = "1.0.0"

return SharedSecretHandler

-- Example setup in kong.yml
-- plugins:
-- - name: shared-secret
--   config:
--     # No additional configuration needed, just enable the plugin
```

## Example Request

```bash
curl -X GET \
  'https://your-api.zuplo.dev/your-route' \
  -H 'Authorization: Bearer YOUR_API_KEY'
```

## Learn More

- [API Key Authentication on Zuplo](https://zuplo.com/docs/policies/api-key-auth-inbound)
- [JWT Authentication on Zuplo](https://zuplo.com/docs/policies/open-id-jwt-auth-inbound)
- [All use cases](https://zuplo.com/use-cases)
