我们只演示在 services 上配置 jwt 认证。
service 开启 jwt 插件
#创建一个需 jwt 验证的服务 成功响应返回 baidu
curl -x POST localhost:8001/services
-d “name=service.jwt”
-d “url=http://www.baidu.com”
# 查看插件列表
curl -x GET localhost:8001/services/service.jwt/plugins
# 开启 jwt 插件
curl -x POST localhost:8001/services/service.jwt/plugins
-d “name=jwt”
# 查看 jwt 插件
curl -x GET localhost:8001/services/service.jwt/plugins/jwt
# 删除 jwt 插件
curl -x DELETE localhost:8001/services/service.jwt/plugins/{jwt.id}
创建 route
为 service.jwt 服务绑定 route
curl -x POST localhost:8001/services/service.jwt/routes
-d “name=route.jwt”
-d “paths[]=/api/v1”
创建一个 consumer
curl -x POST localhost:8001/consumers \
-d “username=consumer.jwt”
{
“custom_id”: null,
“created_at”: 1553681695,
“username”: “consumer.jwt”,
“id”: “2e34d380-ec48-4a0d-926f-6dd8696a7eca”
}
创建 consumer 的 jwt 凭证
可以指定算法 algorithm,iss 签发者 key,密钥 secret,也可以省略,会自动生成。
curl -x POST localhost:8001/consumers/consumer.jwt/jwt \
-d “algorithm=HS256” \
-d “key=big_cat” \
-d “secret=uFLMFeKPPL525ppKrqmUiT2rlvkpLc9u”
//response
{
“rsa_public_key”: null,
“created_at”: 1553681782,
“consumer”: {
“id”: “2e34d380-ec48-4a0d-926f-6dd8696a7eca”
},
“id”: “61ee520c-3387-42f0-8e5f-02e0dc34d3d4”,
“algorithm”: “HS256”,
“secret”: “uFLMFeKPPL525ppKrqmUiT2rlvkpLc9u”,
“key”: “7Xc3L8TdFpU6kgPEeR4iqMAstqLewJSS”
}
查看 consumer jwt 凭证
curl -x GET localhost:8001/consumers/comsumer.jwt/jwt
// 这里我们创建了 2 个 jwt 凭证
{
“next”: null,
“data”: [
{
“rsa_public_key”: null,
“created_at”: 1553682659,
“consumer”: {
“id”: “2e34d380-ec48-4a0d-926f-6dd8696a7eca”
},
“id”: “6966cec4-6d25-4642-983b-95e512eef608”,
“algorithm”: “HS384”,
“secret”: “WF3Ig85MgyGMZjvSCoKLOwOevZkD8jNG”,
“key”: “big_cat”
},
{
“rsa_public_key”: null,
“created_at”: 1553681990,
“consumer”: {
“id”: “2e34d380-ec48-4a0d-926f-6dd8696a7eca”
},
“id”: “e3d34707-0f4f-4c2d-ae54-25aaed6c9211”,
“algorithm”: “HS256”,
“secret”: “yBcPzjWsaW0dMquiWCOGlH2ILDQfJIya”,
“key”: “wP7ZxrL4OgMVViwE8GYcaYq57cVa2IHL”
}
]
}
jwt 下发
业务服务器根据 kong 生成的 jwt 凭证中的 algorithm、key(iss)、secret 进行 token 的演算和下发。请求鉴权接口需携带 Authorization: Bearer jwt 进行请求。测试的话可以用 https://jwt.io 生成:
请求带有 jwt 认证的服务的路由
curl -X GET localhost:8000/api/v1 \
-H ‘Authorization: Bearer eyJhbGciOiJIUzM4NCIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJiaWdfY2F0Iiwic3ViIjoiMTIzNDU2Nzg5MCIsIm5hbWUiOiJKb2huIERvZSIsImlhdCI6MTUxNjIzOTAyMn0.8yO2FmP23u2sS3kq94B39uT23SU2WVNuslPTeSJaHfBLoCT4oNmFTODfHS3s6sot’
// 返回了 baidu 首页
<html>
<head>
<script>
location.replace(location.href.replace(“https://”,”http://”));
</script>
</head>
<body>
<noscript>
<meta http-equiv=”refresh” content=”0;url=http://www.baidu.com/”>
</noscript>
</body>
</html>
否则
// 401
{
“message”: “Unauthorized”
}