Authentication overview

Kong API Gateway manages authentication and authorization for API consumers by acting as a reverse proxy that sits in front of your upstream services. When a request is received, Kong can be configured to execute authentication plugins before forwarding the request to the upstream service. This approach centralizes security concerns at the gateway level, abstracting authentication logic from individual microservices. Kong's plugin architecture allows for flexible configuration and integration with various identity providers and security protocols Kong Gateway getting started guide.

The core concept involves defining 'Consumers' within Kong, which represent users or services that consume your APIs. Each Consumer can be associated with one or more sets of credentials for different authentication methods. When a request arrives, Kong identifies the Consumer based on the provided credentials (e.g., API key, JWT token) and, if successful, allows the request to proceed. This mechanism supports fine-grained access control and rate limiting on a per-Consumer basis Kong Admin API Consumer object reference.

Supported authentication methods

Kong API Gateway supports a variety of authentication methods through its plugin system. These plugins are configurable per API Service or Route, allowing for different authentication requirements across various endpoints. Developers can select the method best suited for their application's security and integration needs Kong Hub plugin list.

Method When to Use Security Level
API Key Simple client-server authentication, internal services, simple mobile apps. Moderate (requires secure key management and transmission).
Basic Authentication Legacy applications, quick integrations, human users with client applications. Moderate (requires HTTPS for secure transmission of credentials).
HMAC Authentication Secure communication between trusted services, integrity verification. High (cryptographic signature ensures authenticity and integrity).
JWT (JSON Web Token) Stateless authentication for microservices, single sign-on (SSO), mobile/web apps. High (signed tokens ensure integrity, can be encrypted for confidentiality).
OAuth 2.0 / OpenID Connect Delegated authorization, third-party applications accessing user data, complex identity flows. High (standardized, robust for various client types, supports refresh tokens).
LDAP Authentication Integrating with existing enterprise directories for user management. High (centralized user management, secure with TLS).
Mutual TLS (mTLS) Strongest identity verification for machine-to-machine communication, highly sensitive APIs. Very High (client and server verify each other's certificates).

Each authentication plugin in Kong provides specific configuration options, such as specifying header names for API keys, validating JWT signatures against a JWKS (JSON Web Key Set) endpoint, or configuring OAuth 2.0 provider details. Kong acts as the enforcement point, offloading these tasks from the backend services Kong Gateway plugin development guide.

Getting your credentials

The process of obtaining and managing credentials in Kong API Gateway varies depending on the chosen authentication method. Generally, it involves configuring Consumers and their associated credentials via Kong's Admin API or declarative configuration files.

  1. For API Key Authentication:
    • Create a Consumer: POST /consumers
    • Generate an API Key for the Consumer: POST /consumers/{consumer_id}/key-auth. Kong generates a unique key that clients will include in their requests (e.g., in the apikey header).
  2. For Basic Authentication:
    • Create a Consumer: POST /consumers
    • Set Basic Auth credentials for the Consumer: POST /consumers/{consumer_id}/basic-auth. Provide a username and password.
  3. For JWT (JSON Web Token) Authentication:
    • Create a Consumer: POST /consumers
    • Configure JWT credentials for the Consumer: POST /consumers/{consumer_id}/jwt. This typically involves providing a key (e.g., the JWT issuer) and a secret (for HMAC-signed tokens) or a rsa_public_key (for RSA-signed tokens). Kong then validates incoming JWTs against these registered credentials.
  4. For OAuth 2.0 / OpenID Connect:
    • This method usually involves an external Authorization Server. Kong's OAuth 2.0 plugin acts as a resource server.
    • Create a Consumer, then configure the OAuth 2.0 plugin on your Service or Route. This setup often involves registering client applications with the external Authorization Server to obtain client_id and client_secret values, which are then used to acquire access tokens OAuth 2.0 specification overview.
    • Kong can be configured to validate tokens issued by the Authorization Server, either by introspection or by validating JWTs.

For declarative configuration, you would define these Consumers and their credentials within a YAML or JSON file that Kong uses for its configuration, simplifying version control and deployment automation Kong declarative configuration reference.

Authenticated request example

The following example demonstrates an API call authenticated with an API Key, assuming a service or route is protected by Kong's Key Authentication plugin.

First, ensure you have set up a Consumer and an API Key within Kong:

# Create a Consumer
curl -X POST http://localhost:8001/consumers \
  --data "username=my-api-consumer"

# Associate an API Key with the Consumer
curl -X POST http://localhost:8001/consumers/my-api-consumer/key-auth \
  --data "key=YOUR_API_KEY_VALUE"

Once the API Key (e.g., YOUR_API_KEY_VALUE) is configured, a client can make an authenticated request by including the key in a designated header (by default, apikey) or as a query parameter.

# Example using curl with API Key in the header
curl -X GET \
  -H "apikey: YOUR_API_KEY_VALUE" \
  http://localhost:8000/my-protected-api/data

# Example using curl with API Key as a query parameter
curl -X GET \
  "http://localhost:8000/my-protected-api/data?apikey=YOUR_API_KEY_VALUE"

Kong will intercept this request, validate the YOUR_API_KEY_VALUE against its stored credentials for the my-api-consumer, and if valid, forward the request to the upstream /my-protected-api/data endpoint. If the key is invalid or missing, Kong will return an authentication error (e.g., HTTP 401 Unauthorized or 403 Forbidden).

Security best practices

Implementing authentication with Kong API Gateway requires adherence to security best practices to protect your APIs and underlying services.

  • Use HTTPS/TLS Everywhere: Always enforce TLS for all traffic to and through Kong API Gateway, including communication between Kong and upstream services. This encrypts credentials and sensitive data in transit, preventing eavesdropping and man-in-the-middle attacks. Kong has built-in support for TLS termination and mTLS Kong Gateway security configuration guides.
  • Strong Credential Management:
    • API Keys: Treat API keys like passwords. Do not hardcode them in client-side code, commit them to version control, or expose them in public repositories. Rotate keys regularly.
    • Secrets: For JWT secrets or OAuth client secrets, use strong, randomly generated values. Store them securely, preferably in secret management systems rather than directly in configuration files.
    • Password Hashing: If managing user passwords directly (e.g., for Basic Auth), always store them as cryptographically hashed values, never plain text.
  • Least Privilege Principle: Grant consumers only the minimum necessary permissions. If using custom authorization logic downstream or with Kong's ACL plugin, ensure that authenticated consumers can only access resources they are explicitly authorized for.
  • Rate Limiting and Throttling: Implement rate limiting plugins to prevent brute-force attacks on authentication endpoints and protect against denial-of-service (DoS) attacks. This limits the number of requests a consumer can make within a given timeframe Kong Rate Limiting plugin documentation.
  • Input Validation: While Kong handles much of the authentication validation, ensure that any custom authentication logic or downstream services perform robust input validation to prevent injection attacks and other vulnerabilities.
  • Error Handling: Provide generic error messages for authentication failures. Avoid revealing specific details (e.g., "invalid username" vs. "invalid password") that could aid attackers in enumeration attempts.
  • Centralized Logging and Monitoring: Log all authentication attempts, successes, and failures. Integrate Kong with a robust monitoring system to detect and alert on suspicious activity, such as a high volume of failed login attempts.
  • Regular Audits: Periodically review your authentication configurations, consumer lists, and credential statuses to ensure they align with your security policies and remove any stale or unnecessary access.