Keycloak 是一个开源的权限管理和认证系统。使用 Keycloak 可以让开发者专注于解决业务的核心问题。获取用户信息是权限管理和认证系统需要的基本功能。Service Account 是OAuth 2.0推荐的系统服务使用的账户,开发者可以通过 Keycloak 的 Service Account 来让自己的微服务去 Keycloak 获取和管理用户信息。
使用 Service Account 获得 token
可以参考我的下面这篇文章了解 Service Account 和获取 token
- https://blog.csdn.net/surfirst/article/details/121601753
给 Service Account 添加访问用户信息的角色
基本步骤如下:
- 登录 Keycloak 的管理页面
- 选择 Service Account 所在的 Client
- 在 Service Account Roles 菜单给 Service Account 添加 view_users 角色
如下图所示。下图选择的是名字为 factory-model 的 client, 在 Service Account Roles 卡片选择 realm-management client 然后给 service client 添加了 view-users权限 :
访问用户信息
使用类似于下面的 curl 命令可以获得 keycloak 某个 realm 的所有用户信息:
curl --location 'https://172.26.196.47:30013/auth/admin/realms/ems/users' \
--header 'Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJjelF3ZElOVkxEVFIzOGNRWktFM2tqT0RMdmF1STI0NGdaei1zOC1EQjcwIn0.eyJleHAiOjE2ODUyODIxMTksImlhdCI6MTY4NTI3ODUxOSwianRpIjoiOGE1Y2EyZmQtMjNlYi00OTgwLTkxOGQtMDdmOWQ3NmU2ZWQzIiwiaXNzIjoiaHR0cHM6Ly8xNzIuMjYuMTk2LjQ3OjMwMDEzL2F1dGgvcmVhbG1zL2VtcyIsImF1ZCI6WyJyZWFsbS1tYW5hZ2VtZW50IiwiYWNjb3VudCJdLCJzdWIiOiIzMThkYjhiNS1kMmZmLTQ5YzMtYTQ1OC1lOGI0NDY3OTk5ZWEiLCJ0eXAiOiJCZWFyZXIiLCJhenAiOiJmYWN0b3J5LW1vZGVsIiwiYWNyIjoiMSIsInJlYWxtX2FjY2VzcyI6eyJyb2xlcyI6WyJkZWZhdWx0LXJvbGVzLWVtcyIsIm9mZmxpbmVfYWNjZXNzIiwidW1hX2F1dGhvcml6YXRpb24iXX0sInJlc291cmNlX2FjY2VzcyI6eyJyZWFsbS1tYW5hZ2VtZW50Ijp7InJvbGVzIjpbInZpZXctdXNlcnMiLCJxdWVyeS1ncm91cHMiLCJxdWVyeS11c2VycyJdfSwiZmFjdG9yeS1tb2RlbCI6eyJyb2xlcyI6WyJ1bWFfcHJvdGVjdGlvbiJdfSwiYWNjb3VudCI6eyJyb2xlcyI6WyJtYW5hZ2UtYWNjb3VudCIsIm1hbmFnZS1hY2NvdW50LWxpbmtzIiwidmlldy1wcm9maWxlIl19fSwic2NvcGUiOiJwcm9maWxlIGVtYWlsIGVtcy1rcGktd3JpdGUiLCJlbWFpbF92ZXJpZmllZCI6ZmFsc2UsImNsaWVudElkIjoiZmFjdG9yeS1tb2RlbCIsImNsaWVudEhvc3QiOiIxMC40Mi4wLjEiLCJwcmVmZXJyZWRfdXNlcm5hbWUiOiJzZXJ2aWNlLWFjY291bnQtZmFjdG9yeS1tb2RlbCIsImNsaWVudEFkZHJlc3MiOiIxMC40Mi4wLjEifQ.aWNAti0SvxIUeFGwd5ZruJxK3lCVC2GeEqZzT9pwT5DBvZbUy55MFvDY3amvzlvPDw2vu4nzw9oBC2FcZX-2634jBsKcQDLHY3cUK1kMZ5dnIXbXOlrCVWUHtlidi0Yy19QzaYO5nD-yWVE_55UFiL3VpNBcJiBQJKTyESUYrlb4VGBv4pCn_86ME-PyvNuQecF759gxkagxyheE19zp1AvXnv0dv9qrP4Xy5U7asJzwHTDFgkP8STv7PiQKEOkQrX9uaq551SsKomF12VKuej31l8IA50-AhrjL8yde-7iH37-i891LeOUg3Xr6XqtoeJBr2waaNcJGUmV_oqYnww'
我们可以得到类似下面的结果:
[{"id": "4a1d2352-5d42-45e1-843b-5ab31545aa94","createdTimestamp": 1625713638941,"username": "admin","enabled": true,"totp": false,"emailVerified": false,"attributes": {"locale": ["en"]},"disableableCredentialTypes": [],"requiredActions": [],"notBefore": 0,"access": {"manageGroupMembership": false,"view": true,"mapRoles": false,"impersonate": false,"manage": false}},```
]