Skip to main content

Key Authentication

Updated Feb 26, 2023 ·

Overview

Key Authentication secures APIs by requiring clients to include an API key in requests. Kong validates the key to allow access.

  • Simple to set up and manage.
  • Clients send the API key via headers, query strings, or cookies.

Lab Environment

This lab tests a Kong API Gateway deployment using a FastAPI endpoint. To simplify, both the containerized Kong API Gateway and the FastAPI endpoint are installed locally on a Windows 10 machine. A Docker Compose file is used to deploy Kong, along with other applications like Prometheus, Zipkin, the ELK Stack, and more.

info

Make sure that you have installed Docker Desktop.

Simply installing Docker in WSL2 without Docker Desktop may introduce some issue when configuring the communication between the containerized Kong API Gateway and the FastAPI application that is installed on the local host.

Pre-requisites

Enable the Key Auth Plugin

To enable the plugin, go to Kong Manager > Plugins > New Plugin > Select Key Authentication.

Set this plugin as a global plugin and enable the following under Plugin Configuration.

  • Key In Header
  • Key In Query

Under key names, specify:

  • apikey
  • token

Under Advanced parameters, enter the following details. Click Save afterwards.

FieldValue
Instance Namekey-authentication

Make sure to disable other global authentication methods. For more information, please see Conflicting Global Authentication Methods

Configure the Key Auth Credentials

To create a consumer, please see Create the Consumer.

Select the consumer and click Credentials > New Key Auth Credential. We can provide our own key or we can let Kong generate a key by simply clicking Save.

The new key should now appear in the credentials page. Copy the key.

Test Key Auth

Setup Postman

To setup Postman, please see Testing with Postman

Go back to Postman and create a new request. Rename it to Testing FastAPI via Kong - Key Auth. Enter the URL below.

http://localhost:8000/kong/healthy 

Click the Headers tab and add the following:

KeyValue
apikeyadd the API key here

Hit Send.