Key Authentication
Apply the key-auth plugin to a route and attach credentials using the KongConsumer and KongCredentialAPIKey CRDs.
Prerequisites
Series Prerequisites
This page is part of the Get Started with the Kong Gateway Operator series.
Complete the previous page, Enable Proxy Caching before completing this page.
Add authentication to the httpbin service
- 
    Create a new key-authplugin.echo " apiVersion: configuration.konghq.com/v1 kind: KongPlugin metadata: name: key-auth namespace: kong annotations: kubernetes.io/ingress.class: kong plugin: key-auth " | kubectl apply -f -Copied!Next, apply the KongPluginresource by annotating theKongKongserviceresource:kubectl annotate -n kong service konghq.com/plugins=rate-limit-5-min,proxy-cache-all-endpoints,key-auth --overwriteCopied!
- 
    Test that the API is secure by sending a request using curl -i $PROXY_IP/anything:curl -i $PROXY_IP/anythingCopied!This request returns a 401error with the messageUnauthorized.You should see the response: HTTP/1.1 401 Unauthorized Date: Wed, 11 Jan 2044 18:33:46 GMT Content-Type: application/json; charset=utf-8 WWW-Authenticate: Key realm="kong" Content-Length: 45 X-Kong-Response-Latency: 1 Server: kong/3.9.1 { "message":"No API key found in request" }Copied!
Set up Consumers and keys
Key authentication in Kong Gateway works by using the Consumer entity. Keys are assigned to Consumers, and client applications present the key within the requests they make.
Keys are stored as Kubernetes Secrets and Consumers are managed with the KongConsumer CRD.
- 
    Create a new Secretlabeled to usekey-authcredential type:echo ' apiVersion: v1 kind: Secret metadata: name: alex-key-auth namespace: kong labels: konghq.com/credential: key-auth stringData: key: hello_world ' | kubectl apply -f -Copied!
- 
    Create a new Consumer and attach the credential: echo " apiVersion: configuration.konghq.com/v1 kind: KongConsumer metadata: name: alex namespace: kong annotations: kubernetes.io/ingress.class: kong username: alex credentials: - alex-key-auth spec: controlPlaneRef: type: konnectNamespacedRef konnectNamespacedRef: name: gateway-control-plane " | kubectl apply -f -Copied!
- 
    Make a request to the API and provide your apikey:curl "$PROXY_IP/anything" \ -H "apikey:hello_world"Copied!The results will return successfully.