使用Curl结合双因素认证获取Keycloak令牌:指定TOTP应用
解决Keycloak多TOTP设备的API认证问题
当你的Keycloak账户绑定多个TOTP设备时,仅传递totp参数会因无法指定具体设备导致认证失败,可按以下步骤解决:
1. 获取目标TOTP设备的ID
首先需要拿到每个TOTP设备对应的credential_id,通过Keycloak管理API查询:
- 先使用管理员账号调用token端点获取管理员访问令牌
- 调用用户凭据查询接口,替换
{user-id}和your-realm为实际值:
curl -X GET 'http://your-keycloak-domain/auth/admin/realms/your-realm/users/{user-id}/credentials' \ -H 'Authorization: Bearer 管理员访问令牌'
返回的JSON中,类型为totp的条目就是你的TOTP设备,每个条目的id即为credential_id,userLabel字段对应你给设备设置的名称(比如私人手机、工作手机),据此找到目标设备的ID。
2. 指定TOTP设备获取认证令牌
在原有token请求中添加credential_id参数,明确指定要使用的TOTP设备,完整curl命令示例:
curl -X POST 'http://your-keycloak-domain/auth/realms/your-realm/protocol/openid-connect/token' \ -H 'Content-Type: application/x-www-form-urlencoded' \ -d 'client_id=你的客户端ID' \ -d 'username=你的用户名' \ -d 'password=你的密码' \ -d 'grant_type=password' \ -d 'totp=当前TOTP验证码' \ -d 'credential_id=目标TOTP设备的ID'
通过上述步骤即可指定对应TOTP设备完成双因素认证,成功获取用于调用Keycloak REST API的令牌。
内容的提问来源于stack exchange,提问作者Xunde Energie
相关产品推荐
相关产品推荐

