"uri":"/anything/*",
"plugins": {
"openid-connect": {
"client_id": "myclient",
"client_secret": "e91CKZQwhxyDqpkP0YFUJBxiXJ0ikJhq",
"discovery": "http://127.0.0.1:8080/realms/myrealm/.well-known/openid-configuration",
"scope": "openid profile",
"bearer_only": false,
"realm": "myrealm",
"redirect_uri": "http://127.0.0.1:9080/anything/callback",
"logout_path": "/anything/logout"
}
},
"upstream":{
"type":"roundrobin",
"nodes":{
"httpbin.org:80":1
}
}
}

screenshot

2. 創建 API 成功后訪問 http://127.0.0.1:9080/anything/test 時,由于未進行登錄,因此將被引導到 Keycloak 的登錄頁面:

screenshot

3. 輸入賬號(myuser)、密碼(mypassword)完成登錄后,成功跳轉到 http://127.0.0.1:9080/anything/test 頁面:

screenshot

4. 訪問 http://127.0.0.1:9080/anything/logout 退出登錄:

screenshot

場景二:使用 AccessToken 驗證身份?

通過啟用 bearer_only 參數對應用之間的調用進行身份認證,此時應用訪問 APISIX 時需攜帶 Authorization Header,否則該請求將被拒絕。

  1. 使用如下命令創建一條 API:
curl -XPUT 127.0.0.1:9080/apisix/admin/routes/1 -H "X-API-KEY: edd1c9f034335f136f87ad84b625c8f1" -d '{
"uri":"/anything/*",
"plugins": {
"openid-connect": {
"client_id": "myclient",
"client_secret": "e91CKZQwhxyDqpkP0YFUJBxiXJ0ikJhq",
"discovery": "http://127.0.0.1:8080/realms/myrealm/.well-known/openid-configuration",
"scope": "openid profile",
"bearer_only": true,
"realm": "myrealm",
"redirect_uri": "http://127.0.0.1:9080/anything/callback",
"logout_path": "/anything/logout"
}
},
"upstream":{
"type":"roundrobin",
"nodes":{
"httpbin.org:80":1
}
}
}'

screenshot

2. 未攜帶 X-Access-Token 訪問 Apache APISIX 時將返回 401 表明未經授權:

screenshot

3. 調用 Keycloak API 獲取 AccessToken:

curl -XPOST "http://127.0.0.1:8080/realms/myrealm/protocol/openid-connect/token" -d "grant_type=password&username=myuser&client_id=myclient&client_secret=e91CKZQwhxyDqpkP0YFUJBxiXJ0ikJhq&password=mypassword"

screenshot

4. 將 AccessToken 放于 Authorization 頭中請求 APISIX(替換掉 ${AccessToken}),可以認證成功:

curl http://127.0.0.1:9080/anything/test -H "Authorization: Bearer ${AccessToken}"

screenshot

場景三:上游服務解析 UserInfo 信息?

當啟用 APISIX set_userinfo_header 配置后,認證成功后回調請求將攜帶 X-Userinfo 請求頭,它包含了 User 的基本信息,可通過 base64_decode 獲得用戶內容。

常見問題?

  1. 為什么 APISIX 中 Cookie 值非常長?

因為 APISIX 會將 id_tokenaccess_tokenrefresh_token 等值寫入 Cookie 中,因此整個 Cookie 內容比較長。具體實現可閱讀 lua-resty-openidc 庫中設置 session 的邏輯。

  1. 如何修改 Session 存儲的 Cookie 名稱、存儲位置?

目前 openid-connect 插件未提供自定義這部分配置的能力,因此可以使用 lua-resty-session 中提供的方法:通過 NGINX 變量的方式對其默認配置進行覆蓋。 此處借助 APISIX 提供的 NGINX 配置注入能力以實現覆蓋:通過在配置文件 {apisix}/conf/config.yaml 中添加這些代碼,可修改 Session 存儲 Cookie 的名稱:

nginx_config:
http_server_configuration_snippet: |
set $session_name "session_override";

原文來源:Protect your API with Keyclone and API Gateway

上一篇:

掌握良好的API設計原則:是什么、為什么以及如何

下一篇:

原型優先API設計
#你可能也喜歡這些API文章!

我們有何不同?

API服務商零注冊

多API并行試用

數據驅動選型,提升決策效率

查看全部API→
??

熱門場景實測,選對API

#AI文本生成大模型API

對比大模型API的內容創意新穎性、情感共鳴力、商業轉化潛力

25個渠道
一鍵對比試用API 限時免費

#AI深度推理大模型API

對比大模型API的邏輯推理準確性、分析深度、可視化建議合理性

10個渠道
一鍵對比試用API 限時免費