API网关第二弹:kong里面添加apikey认证的服务

250 阅读3分钟

著名的天气网站,大家可以随时注册并且拿到API KEY

我就把已经验证过的这个天气服务,对应到我自己的kong网关里面来管理

要在 Kong API Gateway 中添加一个查询天气的服务,你需要执行以下步骤:

1. 创建服务(Service)

首先,你需要在 Kong 中创建一个服务,这个服务将代理 http://api.openweathermap.org/data/2.5/weather 这个 API。

curl -i -X POST \
  --url http://localhost:8001/services/ \
  --data "name=weather_service" \
  --data "url=http://api.openweathermap.org/data/2.5/weather"

这里,name 是你为服务定义的名称(例如 weather_service),url 是后端服务的 URL。

你会看到如下截图的结果

image.png

2. 创建路由(Route)

接下来,为 weather_service 创建一个路由,定义客户端请求的路径。

curl -i -X POST \
  --url http://localhost:8001/services/weather_service/routes \
  --data "paths[]=/weather"

这里,paths 参数定义了客户端可以访问的路径,/weather 表示所有以 /weather 开头的请求都将被转发到 weather_service

服务也创建ok

image.png

PS:要注意,指令中并没有对routes的名字进行命名,所以一开始在kong的管理页面,你会看到name那边是空的,后续你可以自己改。

3. 创建消费者(Consumer)

在 Kong 中,每个通过 API 进行的请求都必须与一个消费者(Consumer)关联。消费者可以是个人或第三方应用程序。

curl -i -X POST \
  --url http://localhost:8001/consumers/ \
  --data "username=weather_app_user"

image.png

这里,username 是你为消费者定义的名称(例如 weather_app_user)。

4. 添加 key-auth 插件

为了保护你的服务,你可以添加一个 key-auth 插件,并将其与消费者关联。

curl -i -X POST \
  --url http://localhost:8001/services/weather_service/plugins/ \
  --data "name=key-auth" \
  --data "config.key_names[]=apikey"

image.png

这里,name 是插件的名称(key-auth),config.key_names 定义了请求中 API 密钥的名称(在这个例子中是 apikey)。

5. 为消费者添加 API 密钥

现在,你需要为之前创建的消费者添加一个 API 密钥。

curl -i -X POST \
  --url http://localhost:8001/consumers/weather_app_user/key-auth/ \
  --data "key=your_api_key"

这里,key 参数是你在 OpenWeatherMap 网站上获取的 API 密钥。

image.png

6. 测试服务

完成上述步骤后,你可以通过 Kong 的代理端口(默认是 8000)来测试你的服务。

curl -i -X GET "http://localhost:8000/weather?q=London&apikey=your_api_key&units=metric"

确保将 your_api_key 替换为你的 OpenWeatherMap API 密钥。

image.png

注意事项

  • 确保 Kong 服务正在运行,并且 Admin API 端口(默认 8001)和代理端口(默认 8000)是可访问的。

  • 替换示例中的 localhost:8001 和 localhost:8000 为你的 Kong 实例的实际地址和端口。

  • 使用正确的 API 密钥和消费者名称。

  • 如果你想要允许匿名访问,可以按照之前提供的步骤创建一个匿名消费者,并在 key-auth 插件中设置 config.anonymous

按照这些步骤,你应该能够成功地在 Kong 中添加并保护你的查询天气服务。