开源软件kong已可实现api gateway,即作为api网关,转发至后端各api,可以减少后端api认证,访问次数限制等的开发,减少端口暴露。该软件主要由Lua
和nginx
实现,后端数据库连接可选Cassandra
和PostgreSQL
本文测试环境kong连接的为本机的Cassandra
(注:kong
版本为0.9.0
,Cassandra
版本为2.2.7
。kong
目前仅支持2.1
,2.2
版本的Cassandra
,参见issue)
kong安装在l10.10.10.52
启动kong
后,默认新增两个端口8000
(用来转发api)8001
(用来设置)
以下示例如何将发送到http://10.10.10.52:8000
的api转发至http://10.10.10.37
其中http
命令为开源软件httpie
用来发送HTTP
请求
add api
设置命令如下:
http POST 10.10.10.52:8001/apis name=demo3 request_host=10.10.10.37 upstream_url="http://10.10.10.37"
测试结果(注:root:root1234
为10.10.10.37
需要的用户认证)
http 10.10.10.52:8000 Host:10.10.10.37 --auth root:root1234
HTTP/1.1 200 OK Allow: GET, HEAD, OPTIONS Connection: keep-alive Content-Type: application/json Date: Thu, 01 Sep 2016 08:29:49 GMT Server: gunicorn/17.5 Transfer-Encoding: chunked Vary: Accept, Cookie Via: kong/0.9.0 X-Frame-Options: SAMEORIGIN X-Kong-Proxy-Latency: 0 X-Kong-Upstream-Latency: 472 jjkre: hello { "groups": "http://10.10.10.37/groups/", "reports": "http://10.10.10.37/reports/", "users": "http://10.10.10.37/users/", "zpassword": "http://10.10.10.37/zpassword/" }
|
增加用户认证
1.http POST 10.10.10.52:8001/apis/demo3/plugins name=key-auth config.key_names=X-AUTH
通过插件开启认证
2.http 10.10.10.52:8000 Host:10.10.10.37 --auth root:root1234
此时通过之前的方法发送请求,会提示未认证
HTTP/1.1 401 Unauthorized Connection: keep-alive Content-Type: application/json; charset=utf-8 Date: Thu, 01 Sep 2016 08:48:19 GMT Server: kong/0.9.0 Transfer-Encoding: chunked WWW-Authenticate: Key realm="kong" { "message": "No API key found in headers or querystring" }
|
3.新增consumers, http POST 10.10.10.52:8001/consumers username=Lily
4.设置密码, http POST 10.10.10.52:8001/consumers/Lily/key-auth key=Lily1234
5.发送api,http 10.10.10.52:8000 Host:10.10.10.37 X-AUTH:Lily1234 --auth root:root1234
此时可以正常发送请求,并得到返回值,如下所示:
HTTP/1.1 200 OK Allow: GET, HEAD, OPTIONS Connection: keep-alive Content-Type: application/json Date: Thu, 01 Sep 2016 08:56:25 GMT Server: gunicorn/17.5 Transfer-Encoding: chunked Vary: Accept, Cookie Via: kong/0.9.0 X-Frame-Options: SAMEORIGIN X-Kong-Proxy-Latency: 0 X-Kong-Upstream-Latency: 335 jjkre: hello { "groups": "http://10.10.10.37/groups/", "reports": "http://10.10.10.37/reports/", "users": "http://10.10.10.37/users/", "zpassword": "http://10.10.10.37/zpassword/" }
|
此软件还有其它功能,例如限制api请求次数等,请查阅官方文档