1-Let's add a KongPlugin resource to protect the API:
$ echo "
apiVersion: configuration.konghq.com/v1
kind: KongPlugin
metadata:
name: httpbin-auth
plugin: key-auth
" | kubectl apply -f -
kongplugin.configuration.konghq.com/httpbin-auth created
2-Now, associate this plugin with the previous Ingress rule we created using the plugins.konghq.com
annotation:
$ echo "
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: demo
annotations:
plugins.konghq.com: httpbin-auth
spec:
rules:
- http:
paths:
- path: /foo
backend:
serviceName: httpbin
servicePort: 80
" | kubectl apply -f -
Any request matching the proxying rules defined in the demo
ingress will now require a valid API key:
$ curl -i $PROXY_IP/foo/status/200
HTTP/1.1 401 Unauthorized
Date: Wed, 17 Jul 2019 19:30:33 GMT
Content-Type: application/json; charset=utf-8
Connection: keep-alive
WWW-Authenticate: Key realm="kong"
Content-Length: 41
Server: kong/1.2.1
{"message":"No API key found in request"}
3-由于服务添加了认证插件,所以客户端访问需要提供凭证,头里需要添加apikey: xxxxx
所以需要创建一个带有访问凭证的消费者
--创建证书
kubectl create secret generic harry-apikey --from-literal=kongCredType=key-auth --from-literal=key=my-sooper-secret-key
--绑定证书到消费者
$ echo "apiVersion: configuration.konghq.com/v1
kind: KongConsumer
metadata:
name: harry
username: harry
credentials:
- harry-apikey" | kubectl apply -f -
kongconsumer.configuration.konghq.com/harry configured
--测试
$ curl -i -H 'apikey: my-sooper-secret-key' $PROXY_IP/foo/status/200
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 0
Connection: keep-alive
Server: gunicorn/19.9.0
Date: Wed, 17 Jul 2019 19:34:44 GMT
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
X-Kong-Upstream-Latency: 3
X-Kong-Proxy-Latency: 1
Via: kong/1.2.1