Support multiple authentication methods

Related Documentation
Related Resources
TL;DR

Create an anonymous consumer that will be used when validation fails. Attach a request-termination plugin to this consumer to ensure that traffic is blocked if the request does not match another consumer’s credentials.

Prerequisites

If you don’t have a Konnect account, you can get started quickly with our onboarding wizard.

  1. The following Konnect items are required to complete this tutorial:
    • Personal access token (PAT): Create a new personal access token by opening the Konnect PAT page and selecting Generate Token.
  2. Set the personal access token as an environment variable:

    export KONNECT_TOKEN='YOUR KONNECT TOKEN'
    
  1. Install the Gateway API CRDs before installing Kong Ingress Controller.

    kubectl apply -f https://github.com/kubernetes-sigs/gateway-api/releases/download/v1.3.0/standard-install.yaml
    
  2. Create a Gateway and GatewayClass instance to use.

echo "
apiVersion: v1
kind: Namespace
metadata:
  name: kong
---
apiVersion: gateway.networking.k8s.io/v1
kind: GatewayClass
metadata:
  name: kong
  annotations:
    konghq.com/gatewayclass-unmanaged: 'true'
spec:
  controllerName: konghq.com/kic-gateway-controller
---
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
  name: kong
spec:
  gatewayClassName: kong
  listeners:
  - name: proxy
    port: 80
    protocol: HTTP
    allowedRoutes:
      namespaces:
         from: All
" | kubectl apply -n kong -f -

Use the Konnect API to create a new CLUSTER_TYPE_K8S_INGRESS_CONTROLLER Control Plane:

CONTROL_PLANE_DETAILS=$(curl -X POST "https://us.api.konghq.com/v2/control-planes" \
     -H "Authorization: Bearer $KONNECT_TOKEN" \
     --json '{
       "name": "My KIC CP",
       "cluster_type": "CLUSTER_TYPE_K8S_INGRESS_CONTROLLER"
     }')

We’ll need the id and telemetry_endpoint for the values.yaml file later. Save them as environment variables:

CONTROL_PLANE_ID=$(echo $CONTROL_PLANE_DETAILS | jq -r .id)
CONTROL_PLANE_TELEMETRY=$(echo $CONTROL_PLANE_DETAILS | jq -r '.config.telemetry_endpoint | sub("https://";"")')

Create mTLS certificates

Kong Ingress Controller talks to Konnect over a connected secured with TLS certificates.

Generate a new certificate using openssl:

openssl req -new -x509 -nodes -newkey rsa:2048 -subj "/CN=kongdp/C=US" -keyout ./tls.key -out ./tls.crt

The certificate needs to be a single line string to send it to the Konnect API with curl. Use awk to format the certificate:

export CERT=$(awk 'NF {sub(/\r/, ""); printf "%s\\n",$0;}' tls.crt);

Next, upload the certificate to Konnect:

curl -X POST "https://us.api.konghq.com/v2/control-planes/$CONTROL_PLANE_ID/dp-client-certificates" \
     -H "Authorization: Bearer $KONNECT_TOKEN" \
     --json '{
       "cert": "'$CERT'"
     }'

Finally, store the certificate in a Kubernetes secret so that Kong Ingress Controller can read it:

kubectl create namespace kong -o yaml --dry-run=client | kubectl apply -f -
kubectl create secret tls konnect-client-tls -n kong --cert=./tls.crt --key=./tls.key
  1. Add the Kong Helm charts:

    helm repo add kong https://charts.konghq.com
    helm repo update
    
  2. Install Kong Ingress Controller using Helm:

    helm install kong kong/ingress -n kong --create-namespace
    
  3. Set $PROXY_IP as an environment variable for future commands:

    export PROXY_IP=$(kubectl get svc --namespace kong kong-gateway-proxy -o jsonpath='{range .status.loadBalancer.ingress[0]}{@.ip}{@.hostname}{end}')
    echo $PROXY_IP
    

This how-to requires some Kubernetes services to be available in your cluster. These services will be used by the resources created in this how-to.

kubectl apply -f https://developer.konghq.com/manifests/kic/echo-service.yaml -n kong

Allowing multiple authentication methods

The default behavior for Kong Gateway authentication plugins is to require credentials for all requests even if a request has been authenticated through another plugin. Configure an anonymous Consumer on your authentication plugins to set authentication options.

Create Consumers

Create two Consumers that use different authentication methods:

  • consumer-1 uses basic-auth
  • consumer-2 uses key-auth
  1. Create a secret to add a basic-auth credential for consumer-1:

     echo '
     apiVersion: v1
     kind: Secret
     metadata:
       name: consumer-1-basic-auth
       namespace: kong
       labels:
         konghq.com/credential: basic-auth
     stringData:
         username: consumer-1
         password: consumer-1-password
     ' | kubectl apply -f -
    
  2. Create a secret to add a key-auth credential for consumer-2:

     echo '
     apiVersion: v1
     kind: Secret
     metadata:
       name: consumer-2-key-auth
       namespace: kong
       labels:
         konghq.com/credential: key-auth
     stringData:
       key: consumer-2-password
     ' | kubectl apply -f -
    
  3. Create a Consumer named consumer-1:

    echo "
    apiVersion: configuration.konghq.com/v1
    kind: KongConsumer
    metadata:
      name: consumer-1
      namespace: kong
      annotations:
        kubernetes.io/ingress.class: kong
    username: consumer-1
    credentials:
    - consumer-1-basic-auth
    " | kubectl apply -f -
    
  4. Create a Consumer named consumer-2:

    echo "
    apiVersion: configuration.konghq.com/v1
    kind: KongConsumer
    metadata:
      name: consumer-2
      namespace: kong
      annotations:
        kubernetes.io/ingress.class: kong
    username: consumer-2
    credentials:
    - consumer-2-key-auth
    " | kubectl apply -f -
    

Secure the service

Once the Consumers and credentials are created, you can add authentication plugins to your Service.

First, create a key-auth plugin. Notice the anonymous configuration option, which means that if no credentials match, the consumer named anonymous is assigned to the request:

echo "
apiVersion: configuration.konghq.com/v1
kind: KongPlugin
metadata:
  name: key-auth
  namespace: kong
  annotations:
    kubernetes.io/ingress.class: kong
config:
  anonymous: anonymous
plugin: key-auth
" | kubectl apply -f -

As Consumer 2 is using basic-auth, we also need to create a basic-auth plugin:

echo "
apiVersion: configuration.konghq.com/v1
kind: KongPlugin
metadata:
  name: basic-auth
  namespace: kong
  annotations:
    kubernetes.io/ingress.class: kong
config:
  anonymous: anonymous
plugin: basic-auth
" | kubectl apply -f -

Next, apply the KongPlugin resource by annotating the service resource:

kubectl annotate -n kong service echo konghq.com/plugins=key-auth,basic-auth --overwrite

Create an anonymous Consumer

Your endpoints are now secure, but neither Consumer can access the endpoint when providing valid credentials. This is because each plugin will verify the Consumer using it’s own authentication method.

To allow multiple authentication methods, create an anonymous Consumer which is the default user if no valid credentials are provided:

echo "
apiVersion: configuration.konghq.com/v1
kind: KongConsumer
metadata:
  name: anonymous
  namespace: kong
  annotations:
    kubernetes.io/ingress.class: kong
username: anonymous
" | kubectl apply -f -

All requests to the API will now succeed as the anonymous Consumer is being used as a default.

To secure the API once again, add a request termination plugin to the anonymous Consumer that returns HTTP 401:

echo "
apiVersion: configuration.konghq.com/v1
kind: KongPlugin
metadata:
  name: request-termination
  namespace: kong
  annotations:
    kubernetes.io/ingress.class: kong
config:
  message: Authentication required
  status_code: 401
plugin: request-termination
" | kubectl apply -f -

Next, apply the KongPlugin resource by annotating the KongConsumer resource:

kubectl annotate -n kong  anonymous konghq.com/plugins=request-termination

Create an HTTPRoute

To route HTTP traffic, you need to create an HTTPRoute or an Ingress resource pointing at your Kubernetes Service.

Validate your configuration

Once the resource has been reconciled, you’ll be able to call the /echo endpoint and Kong Gateway will route the request to the echo service.

Let’s check that authentication works.

Try to access the Gateway Service via the /anything Route using a nonsense API key:

curl "$PROXY_IP/echo" \
     -H "apikey:nonsense"
curl "$PROXY_IP/echo" \
     -H "apikey:nonsense"

The request should now fail with a 401 response and your configured error message, as this Consumer is considered anonymous.

You should get the same result if you try to access the Route without any API key:

curl "$PROXY_IP/echo"
curl "$PROXY_IP/echo"

Finally, try accessing the Route with the configured basic auth credentials:

curl "$PROXY_IP/echo" \
     -u consumer-1:consumer-1-password
curl "$PROXY_IP/echo" \
     -u consumer-1:consumer-1-password

This time, authentication should succeed with a 200.

Cleanup

kubectl delete -n kong -f https://developer.konghq.com/manifests/kic/echo-service.yaml
helm uninstall kong -n kong
Something wrong?

Help us make these docs great!

Kong Developer docs are open source. If you find these useful and want to make them better, contribute today!