Skip to content

API Gateway Security: Kong & Keycloak

CoreConceptAugust 3, 20269 min read

In microservices architectures, handling authentication, authorization, and rate limiting individually inside every backend service leads to duplicated code, inconsistent security configurations, and increased attack surfaces. If an engineering team updates JWT validation logic or OAuth2 scopes, dozens of microservices must be updated and redeployed simultaneously.

Kong API Gateway paired with Keycloak (an open-source Identity and Access Management solution) solves this problem by centralizing perimeter security. Kong handles high-throughput routing, rate limiting, and JWT token validation at the edge using the OpenID Connect (OIDC) plugin, delegating user identity and SSO authentication to Keycloak. This guide details Kong-Keycloak OIDC integration, claims extraction, and rate-limiting security policies.

Kong API Gateway and Keycloak identity management architecture with OIDC authentication
Kong API Gateway and Keycloak identity management architecture with OIDC authentication

Mental Model: Centralized Gateway Authentication vs Decentralized Microservice Auth

Decentralized authentication requires every backend microservice (Orders, Payments, Users) to validate incoming HTTP Authorization headers, parse JWT signatures, and handle identity provider public key rotations. This creates heavy code overhead and security vulnerability risks.

Centralized Gateway Authentication positions Kong API Gateway as the entry point to your infrastructure.

Kong intercepts all client HTTP requests, validates OAuth2 access tokens against Keycloak's OIDC discovery endpoints, strips sensitive client credentials, and forwards sanitized headers (X-Consumer-ID, X-User-Roles) to upstream microservices. Upstream services operate securely inside a private network, trusting the gateway to sanitize perimeter traffic. For security best practices, review securing rest apis oauth2 jwt best practices and securing microservices istio service mesh mtls.

Kong API Gateway OIDC authentication lifecycle with Keycloak JWKS verification and upstream header injection
Kong API Gateway OIDC authentication lifecycle with Keycloak JWKS verification and upstream header injection

Quick reference

  • Kong API Gateway centralizes perimeter authentication, authorization, and rate limiting.
  • Keycloak acts as the central Identity Provider managing user realms, SSO, and OAuth2 clients.
  • Kong OIDC plugin validates JWT signatures using Keycloak JWKS (JSON Web Key Set) public keys.
  • Upstream microservices receive pre-validated consumer headers, eliminating JWT parsing code.
  • Protects private backend microservices behind a single hardened public gateway URL.

Remember this

Centralize perimeter security at Kong API Gateway to validate Keycloak tokens before routing requests upstream.

Kong OpenID Connect (OIDC) Plugin Configuration with Keycloak Realm

Configuring Kong's OIDC plugin connects the gateway directly to Keycloak's OpenID discovery endpoint (/realms/{realm}/.well-known/openid-configuration).

Configure the Kong OIDC plugin via Declarative Configuration (kong.yml) or Deck CLI:

1plugins:2- name: oidc3  config:4    issuer: http://keycloak:8080/realms/production5    client_id: kong-gateway-client6    client_secret: ${KEYCLOAK_CLIENT_SECRET}7    bearer_only: "yes"8    realm: production

When bearer_only: "yes" is set, Kong acts as a Resource Server, inspecting incoming Authorization: Bearer <JWT> tokens for API requests without initiating browser redirect loops.

Quick reference

  • OIDC plugin auto-discovers Keycloak token endpoints, authorization URIs, and JWKS public keys.
  • bearer_only mode configures Kong as an API Resource Server that validates Bearer JWT tokens.
  • Caches Keycloak JWKS public keys in Redis or shared memory to avoid network latency on every request.
  • Rejects expired, tampered, or invalidly signed JWTs with sub-2ms 401 Unauthorized responses.
  • Supports dynamic multi-realm routing based on HTTP host headers or request paths.

Remember this

Configure the Kong OIDC plugin in bearer_only mode to validate Keycloak JWTs against JWKS endpoints.

JWT Signature Verification, Claims Extraction, & Consumer Mapping

Upon validating the Keycloak JWT signature, Kong extracts payload claims (such as sub, preferred_username, and realm_access.roles).

Kong maps the Keycloak sub claim to an internal Kong Consumer entity. It then injects custom HTTP headers into the upstream request: - X-User-ID: c84f91e2-45a1-4122-b912-881294821 - X-User-Roles: admin,editor - X-User-Email: user@company.com

Upstream microservices read these injected headers directly to enforce internal authorization logic without executing expensive database user lookups or cryptographic signature checks.

Kong API Gateway OIDC authentication lifecycle with Keycloak JWKS verification and upstream header injection
Kong API Gateway OIDC authentication lifecycle with Keycloak JWKS verification and upstream header injection

Quick reference

  • Extracts JWT claims (sub, email, roles) and injects clean HTTP headers into upstream requests.
  • Maps Keycloak sub UUIDs to persistent Kong Consumer entities for rate-limiting tracking.
  • Strips client Authorization headers before forwarding requests to private upstream services.
  • Enables upstream microservices to access pre-parsed user context in zero execution time.
  • Prevents internal header spoofing by stripping untrusted client-supplied X-User headers at the gateway.

Remember this

Extract Keycloak JWT claims in Kong and inject X-User headers to simplify upstream microservice code.

Rate Limiting, IP Restriction, & Access Control Policies

Protecting microservices against Denial of Service (DoS) attacks and credential brute-forcing requires layering security plugins in Kong.

Combine the Rate Limiting Plugin (rate-limiting) with Keycloak Consumer mappings. Configure per-tier rate limits based on user role claims (e.g., standard users: 100 req/min; premium users: 5,000 req/min):

1plugins:2- name: rate-limiting3  config:4    minute: 1005    policy: redis6    redis_host: redis

Add IP Restriction plugins to whitelist internal corporate IP ranges for administrative routes (/admin/*) and enforce TLS 1.3 encryption across all public gateway endpoints.

Quick reference

  • Rate Limiting plugin tracks requests per consumer ID or IP address using Redis storage.
  • Assigns dynamic rate limits based on Keycloak user subscription tiers or role claims.
  • IP Restriction plugin blocks unauthorized external IP addresses from accessing admin routes.
  • Enforces HTTPS TLS 1.3 encryption and HSTS headers on all public gateway listener ports.
  • Logs security audit events (429 Rate Exceeded, 403 Forbidden) to Grafana Loki or Datadog.

Remember this

Layer Kong Rate Limiting and IP Restriction plugins to protect upstream microservices from DoS attacks.

Key takeaway

To test Kong and Keycloak, deploy Kong and Keycloak via Docker Compose. Obtain an access token from Keycloak (/protocol/openid-connect/token) and send an authenticated request through Kong Gateway.

Share:

Related Articles

When external partner systems, automated cron daemons, or background backend microservices need to communicate securely

Read

Traditional perimeter-based security ('Castle and Moat') assumes that all traffic inside a private network or Kubernetes

Read

Five Docker containers with REST between them is not a production microservices system. Clients hit a load balancer and

Read

Keep learning

Follow a structured path or browse all courses to go deeper.