bingshiwuyu 2019-07-01
我们只演示在 services
上配置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}
为service.jwt
服务绑定route
curl -X POST localhost:8001/services/service.jwt/routes -d "name=route.jwt" -d "paths[]=/api/v1"
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" }
可以指定算法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" }
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" } ] }
业务服务器根据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" }