---
title: "Use Kubernetes API Gateway Plugins"
description: "Learn how to run plugins in a Kubernetes AP Gateway"
url: "https://curity.io/resources/learn/integrating-plugins-with-kubernetes-ingress/"
date: "2025-02-13"
area: "tutorials"
topic: "howtos"
pagegroup: "kubernetes"
repository: "https://github.com/curityio/kubernetes-training"
---

# Use Kubernetes API Gateway Plugins

The [Expose OAuth Endpoints from Kubernetes](https://curity.io/resources/learn/kubernetes-ingress/) tutorial explains how to use an API gateway to enable ingress into a cluster. A gateway is a hosting best practice rather than exposing APIs or the authorization server directly to the internet. Many organizations handle cross-cutting concerns in the gateway and then route requests to load balanced Kubernetes services. Using a central point of ingress also saves costs as it reduces the number of load balancers.

## API Gateway Extensibility

Different API gateways provide varying levels of extensibility and customization. Some may require plugins to use low level languages like C, whereas some NGINX derived gateways, like Kong Open Source, provide support for writing plugins in higher level languages like LUA. Kong has a wide range of plugins to support customization use cases.

This tutorial summarizes the Kubernetes specific aspects of integrating the Phantom Token and OAuth Proxy plugins. It explains the Kubernetes specific setups using Kong and NGINX ingress as two representatives for cloud-native API gateways. The following tutorials provide further information, such as how to produce a custom Docker image containing each plugin and its dependencies.

-   [Kong Phantom Token Plugin](https://curity.io/resources/learn/integration-kong-open-source/)
-   [NGINX Phantom Token Module](https://curity.io/resources/learn/nginx-phantom-token-module/)
-   [Kong OAuth Proxy Plugin](https://curity.io/resources/learn/kong-oauth-proxy/)
-   [NGINX OAuth Proxy Module](https://curity.io/resources/learn/nginx-oauth-proxy/)

## Phantom Token Integration

Kong provides a custom resource definition called `KongPlugin` to enable the plugin configuration to be expressed once. For the phantom token plugin, apply YAML settings in the following format for all namespaces that run the plugin in front of API routes:

```yaml
kind: KongPlugin
apiVersion: configuration.konghq.com/v1
metadata:
  name: phantom-token
plugin: phantom-token
config:
  introspection_endpoint: http://curity-idsvr-runtime-svc.curity:8443/oauth/v2/oauth-introspect
  client_id: api-gateway-client
  client_secret: Password1
  token_cache_seconds: 900
```

Then, create an API gateway route that applies the `KongPlugin` resource using an annotation. Create `Ingress` or `HttpRoute` resources for the namespace of the upstream Kubernetes service:

**HTTP Route**

```yaml
kind: HTTPRoute
apiVersion: gateway.networking.k8s.io/v1
metadata:
  name: demoapi-route
  annotations:
    konghq.com/plugins: phantom-token
spec:
  parentRefs:
  - name: kong-gateway
    namespace: kong
  hostnames:
  - api.demoapp.example
  rules:
  - matches:
    - path:
        value: /
    backendRefs:
    - name: demoapi-svc
      kind: Service
      port: 8000
```

**Ingress**

```yaml
kind: Ingress
apiVersion: networking.k8s.io/v1
metadata:
  name: demoapi-ingress
  annotations:
    konghq.com/plugins: phantom-token
spec:
spec:
  ingressClassName: kong
  rules:
  - host: api.demoapp.example
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: demoapi-svc
            port:
              number: 8000
```

For the NGINX API gateway, configure settings differently for the NGINX gateway fabric or the NGINX ingress controller. Use the settings explained in the [NGINX Phantom Token Module](https://curity.io/resources/learn/nginx-phantom-token-module/) tutorial.

**HTTP Route**

To configure the NGINX gateway fabric, use the [SnippetsFilter API](https://docs.nginx.com/nginx-gateway-fabric/how-to/traffic-management/snippets/). Extract plugin settings that require contexts like `main`, `http` and `http.server` into a base snippet. Then put `http.server.location` context settings into its own snippet.

```yaml
apiVersion: gateway.nginx.org/v1alpha1
kind: SnippetsFilter
metadata:
  name: phantom-token-base
spec:
  snippets:  
    - context: main
      value: load_module /usr/lib/nginx/modules/ngx_curity_http_phantom_token_module.so;
    - context: http
      value: proxy_cache_path cache levels=1:2 keys_zone=api_cache:10m max_size=10g inactive=60m use_temp_path=off;
    - context: http.server
      value: |
        location curity {
            internal;
            proxy_pass_request_headers off;
            proxy_set_header Accept "application/jwt";
            proxy_set_header Content-Type "application/x-www-form-urlencoded";
            proxy_set_header Authorization "Basic YXBpLWdhdGV3YXktY2xpZW50OlBhc3N3b3JkMQ==";
            proxy_cache_methods POST;
            proxy_cache api_cache;
            proxy_cache_key $request_body;
            proxy_ignore_headers Set-Cookie;
            proxy_pass http://curity-idsvr-runtime-svc.curity.svc.cluster.local:8443/oauth/v2/oauth-introspect;
        }
---
apiVersion: gateway.nginx.org/v1alpha1
kind: SnippetsFilter
metadata:
  name: phantom-token
spec:
  snippets:
    - context: http.server.location
      value: |
        phantom_token on;
        phantom_token_introspection_endpoint curity;
```

Then reference snippets in the `HTTPRoute` configuration.

```yaml
kind: HTTPRoute
apiVersion: gateway.networking.k8s.io/v1
metadata:
  name: demoapi-route
spec:
  parentRefs:
  - name: nginx-gateway
    namespace: nginx
  hostnames:
  - api.demoapp.example
  rules:
  - matches:
    - path:
        value: /
    filters:
    - type: ExtensionRef
      extensionRef:
        group: gateway.nginx.org
        kind: SnippetsFilter
        name: phantom-token-base
    - type: ExtensionRef
      extensionRef:
        group: gateway.nginx.org
        kind: SnippetsFilter
        name: phantom-token
    backendRefs:
    - name: demoapi-svc
      kind: Service
      port: 8000
```

**Ingress**

To configure the NGINX ingress controller, use a [main-snippet](https://kubernetes.github.io/ingress-nginx/user-guide/nginx-configuration/configmap/#main-snippet) in the NGINX `ConfigMap` to load the module and an [http-snippet](https://kubernetes.github.io/ingress-nginx/user-guide/nginx-configuration/configmap/#http-snippet) to configure the result cache:

```text
main-snippet: load_module /usr/lib/nginx/modules/ngx_curity_http_phantom_token_module.so;
http-snippet: proxy_cache_path cache levels=1:2 keys_zone=api_cache:10m max_size=10g inactive=60m use_temp_path=off;
```

Then use `nginx.ingress.kubernetes.io/configuration-snippet` and `nginx.ingress.kubernetes.io/server-snippet` annotations to inject plugin configuration into the `nginx.conf` file.

```yaml
kind: Ingress
apiVersion: networking.k8s.io/v1
metadata:
  name: demoapi-ingress
  annotations:
    nginx.ingress.kubernetes.io/configuration-snippet: |
        phantom_token on;
        phantom_token_introspection_endpoint curity;
    nginx.ingress.kubernetes.io/server-snippet: |
        location curity {
            internal;
            proxy_pass_request_headers off;
            proxy_set_header Accept "application/jwt";
            proxy_set_header Content-Type "application/x-www-form-urlencoded";
            proxy_set_header Authorization "Basic YXBpLWdhdGV3YXktY2xpZW50OlBhc3N3b3JkMQ==";
            proxy_cache_methods POST;
            proxy_cache api_cache;
            proxy_cache_key $request_body;
            proxy_ignore_headers Set-Cookie;
            proxy_pass http://curity-idsvr-runtime-svc.curity.svc.cluster.local:8443/oauth/v2/oauth-introspect;
        }
spec:
  ingressClassName: nginx
  rules:
  - host: api.demoapp.example
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: demoapi-svc
            port:
              number: 8000
```

The following example tutorials show how to integrate the phantom token plugin with NGINX in the main cloud Kubernetes systems. The GKE deployment can also integrate with the Kong gateway:

-   [Google Kubernetes Engine (GKE)](https://curity.io/resources/learn/kubernetes-gke-idsvr-kong-phantom/)
-   [AWS Elastic Kubernetes Service (EKS)](https://curity.io/resources/learn/kubernetes-aws-eks-idsvr-deployment/)
-   [Azure Kubernetes Service (AKS)](https://curity.io/resources/learn/kubernetes-azure-aks-idsvr-deployment/)

## OAuth Proxy Integration

To pre-process cookies during API requests for the Kong API gateway, follow a similar approach to configure both CORS and the OAuth Proxy plugin:

```yaml
kind: KongPlugin
apiVersion: configuration.konghq.com/v1
metadata:
  name: cors
plugin: cors
config:
  origins:
  - https://www.demoapp.example
  credentials: true
  max_age: 86400
---
kind: KongPlugin
apiVersion: configuration.konghq.com/v1
metadata:
  name: oauth-proxy
plugin: oauth-proxy
config:
  cookie_key: "$TH_COOKIE_KEY"
  cookie_key_pass: "$TH_COOKIE_KEY_PASS"
```

Then, create an API gateway route that applies the `KongPlugin` resources using an annotation. Create `Ingress` or `HttpRoute` resources for the namespace of the upstream Kubernetes service:

**HTTP Route**

```yaml
kind: HTTPRoute
apiVersion: gateway.networking.k8s.io/v1
metadata:
  name: demoapi-route
  annotations:
    konghq.com/plugins: cors,oauth-proxy
spec:
  parentRefs:
  - name: kong-gateway
    namespace: kong
  hostnames:
  - api.demoapp.example
  rules:
  - matches:
    - path:
        value: /
    backendRefs:
    - name: demoapi-svc
      kind: Service
      port: 8000
```

**Ingress**

```yaml
kind: Ingress
apiVersion: networking.k8s.io/v1
metadata:
  name: demoapi-ingress
  annotations:
    konghq.com/plugins: cors,oauth-proxy
spec:
spec:
  ingressClassName: kong
  rules:
  - host: api.demoapp.example
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: demoapi-svc
            port:
              number: 8000
```

For the NGINX API gateway, configure settings differently for the NGINX gateway fabric or the NGINX ingress controller.

**HTTP Route**

To configure the NGINX gateway fabric, express the settings in `SnippetsFilter` resources. Extract the `main` context that loads the module into a base snippet. Then put `http.server.location` context settings into its own snippet.

```yaml
apiVersion: gateway.nginx.org/v1alpha1
kind: SnippetsFilter
metadata:
  name: oauth-proxy-base
spec:
  snippets:
    - context: main
      value: load_module /usr/lib/nginx/modules/ngx_curity_http_phantom_token_module.so;
---
apiVersion: gateway.nginx.org/v1alpha1
kind: SnippetsFilter
metadata:
  name: oauth-proxy
spec:
  snippets:
    - context: http.server.location
      value: |
        set $cors_mode '';
        if ($http_origin = 'http://www.demoapp.example') {
            set $cors_mode 'matched';
        }

        if ($request_method = 'OPTIONS') {
            set $cors_mode '${cors_mode}-preflight';
        }

        if ($cors_mode = 'matched') {
            add_header 'access-control-allow-origin' $http_origin always;
            add_header 'access-control-allow-credentials' true always;
            add_header 'vary' 'origin';
        }

        if ($cors_mode = 'matched-preflight') {
            add_header 'access-control-allow-origin' $http_origin;
            add_header 'access-control-allow-credentials' true;
            add_header 'access-control-allow-methods' 'GET,POST,PUT,PATCH,DELETE';
            add_header 'access-control-allow-headers' $http_access_control_request_headers;
            add_header 'access-control-max-age' 86400;
            add_header 'vary' 'origin, access-control-request-headers';
            return 200;
        }
        
        oauth_proxy on;
        oauth_proxy_key "${TH_COOKIE_KEY}" "${TH_COOKIE_KEY_PASS}";
```

Then reference snippets in the `HTTPRoute` configuration.

```yaml
kind: HTTPRoute
apiVersion: gateway.networking.k8s.io/v1
metadata:
  name: demoapi-route
spec:
  parentRefs:
  - name: nginx-gateway
    namespace: nginx
  hostnames:
  - api.demoapp.example
  rules:
  - matches:
    - path:
        value: /
    filters:
    - type: ExtensionRef
      extensionRef:
        group: gateway.nginx.org
        kind: SnippetsFilter
        name: oauth-proxy-base
    - type: ExtensionRef
      extensionRef:
        group: gateway.nginx.org
        kind: SnippetsFilter
        name: oauth-proxy
    backendRefs:
    - name: demoapi-svc
      kind: Service
      port: 8000
```

**Ingress**

To configure the NGINX ingress controller, first load the module in a `main-snippet` in the NGINX `ConfigMap`:

```text
main-snippet: load_module /usr/lib/nginx/modules/ngx_http_oauth_proxy_module.so;
```

Then use an `nginx.ingress.kubernetes.io/configuration-snippet` annotation to inject plugin configuration into the `nginx.conf` file. The following example settings provide a working CORS solution.

```yaml
kind: Ingress
apiVersion: networking.k8s.io/v1
metadata:
  name: demoapi-ingress
  annotations:
    nginx.ingress.kubernetes.io/configuration-snippet: |
        set $cors_mode '';
        if ($http_origin = 'http://www.demoapp.example') {
            set $cors_mode 'matched';
        }

        if ($request_method = 'OPTIONS') {
            set $cors_mode '${cors_mode}-preflight';
        }

        if ($cors_mode = 'matched') {
            add_header 'access-control-allow-origin' $http_origin always;
            add_header 'access-control-allow-credentials' true always;
            add_header 'vary' 'origin';
        }

        if ($cors_mode = 'matched-preflight') {
            add_header 'access-control-allow-origin' $http_origin;
            add_header 'access-control-allow-credentials' true;
            add_header 'access-control-allow-methods' 'GET,POST,PUT,PATCH,DELETE';
            add_header 'access-control-allow-headers' $http_access_control_request_headers;
            add_header 'access-control-max-age' 86400;
            add_header 'vary' 'origin, access-control-request-headers';
            return 200;
        }
        
        oauth_proxy on;
        oauth_proxy_key "${TH_COOKIE_KEY}" "${TH_COOKIE_KEY_PASS}";
spec:
  ingressClassName: nginx
  rules:
  - host: api.demoapp.example
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: demoapi-svc
            port:
              number: 8000
```

## Deployment Example

The GitHub link at the top of this page provides some Kubernetes deployment examples that run on a local computer. The `Curity Token Handler` example provides a completed backend deployment and also an example Single Page Application, so that you can run an end-to-end flow.

## Conclusion

The leading cloud native API gateways enable advanced API behaviors with plugins or modules. Using annotations and custom resources, API gateways can pre-process requests to convert opaque access tokens or HTTP cookies into JWT access tokens for upstream APIs. These patterns enable clients to follow security best practices and APIs to only work with JWT access tokens.
