Agent-Lab 如何使用 Keycloak
Keycloak 通过 OpenID Connect 管理认证与授权。当 auth.enabled 为 true 时(参见配置参考):
- FastAPI 中间件会在每个请求上依据 realm 的 JWKS 校验 bearer 令牌,并带有标准的排除路径(
/auth/*、/status/*、/docs、/openapi.json、/mcp、/static); /auth路由提供登录、续期、用户资料以及 Microsoft Entra ID 令牌交换端点;- MCP 服务器通过由同一 realm 支撑的 OAuth 代理对客户端进行认证,并发布标准的
.well-known元数据端点。
配置 realm、客户端和服务账号
以下步骤使用 Keycloak Admin API。首先设置管理员凭据和端点:
export ADMIN_USER=<admin_username>
export ADMIN_PASS=<admin_password>
export ADMIN_TOKEN=$(curl -s -X POST "https://<auth_fqdn>/realms/master/protocol/openid-connect/token" \
-d "username=${ADMIN_USER}&password=${ADMIN_PASS}&grant_type=password&client_id=admin-cli" | jq -r '.access_token')创建 realm(将 <realm_name> 替换为实际名称):
curl -X POST https://<auth_fqdn>/admin/realms \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ${ADMIN_TOKEN}" \
-d '{"realm": "<realm_name>", "enabled": true}'为 Agent-Lab 创建客户端:
curl -X POST https://<auth_fqdn>/admin/realms/<realm_name>/clients \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ${ADMIN_TOKEN}" \
-d '{
"clientId": "<client_name>",
"enabled": true,
"protocol": "openid-connect",
"publicClient": false,
"redirectUris": ["https://<agent_lab_fqdn>/*"],
"standardFlowEnabled": true,
"clientAuthenticatorType": "client-secret"
}'获取客户端密钥:
export CLIENT_ID=$(curl -X GET "https://<auth_fqdn>/admin/realms/<realm_name>/clients?clientId=<client_name>" \
-H "Authorization: Bearer ${ADMIN_TOKEN}" | jq -r '.[0].id')
export CLIENT_SECRET=$(curl -X GET "https://<auth_fqdn>/admin/realms/<realm_name>/clients/${CLIENT_ID}/client-secret" \
-H "Authorization: Bearer ${ADMIN_TOKEN}" | jq -r '.value')这些值对应 auth.* 配置键(auth.url、auth.realm、auth.client_id、auth.client_secret)——请按照配置参考将它们存入 Vault 载荷。
创建服务账号用户:
curl -X POST https://<auth_fqdn>/admin/realms/<realm_name>/users \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ${ADMIN_TOKEN}" \
-d '{
"username": "<username>",
"enabled": true,
"email": "<username>@example.com",
"credentials": [{"type": "password", "value": "<user_password>", "temporary": false}]
}'如有需要,可在 Keycloak UI 中微调角色和映射器(mapper)。
签发与验证令牌
获取用户令牌(密码授权模式——与应用端 POST /auth/login 执行的流程相同):
export USER_TOKEN=$(curl -s -X POST https://<auth_fqdn>/realms/<realm_name>/protocol/openid-connect/token \
-d "grant_type=password" \
-d "client_id=<client_name>" \
-d "client_secret=${CLIENT_SECRET}" \
-d "username=<username>" \
-d "password=<user_password>" | jq -r '.access_token')
curl -s https://<agent_lab_fqdn>/agents/list -H "Authorization: Bearer $USER_TOKEN" | jq令牌可通过 POST /auth/renew 续期;已在 Microsoft Entra ID 中完成认证的用户,可以通过 POST /auth/exchange 换取应用令牌(PKCE 授权码流程,由配置中的 Entra ID 凭据提供支持)。
自动化预置
Terraform 模块 terraform/12_agent-lab-auth-realm/(部署指南的一部分)会为参考部署预置 realm、客户端和服务账号——在真实环境中请使用该模块,而不是手动执行上述步骤。