Keycloak模拟身份问题:生成的令牌AZP字段对应错误客户端
Keycloak Token Exchange: AZP Remains Impersonator-Client Instead of Target-Client & Permission Configuration Confusion
1. Fix for AZP Field Mismatch
The main reason your azp claim stays as impersonator-client instead of target-client is a missing critical parameter in your token exchange request. Here's how to correct it:
Your current curl command only sets audience=target-client, but to generate an access token issued to (and with azp set to) target-client, you need to add the requested_client_id parameter. Adding an explicit requested_token_type also eliminates ambiguity for Keycloak.
Updated curl command:
curl -v -X POST \ -d "client_id=impersonator-client" \ -d "client_secret=<secret omitted>" \ --data-urlencode "grant_type=urn:ietf:params:oauth:grant-type:token-exchange" \ -d "audience=target-client" \ -d "requested_client_id=target-client" \ --data-urlencode "requested_token_type=urn:ietf:params:oauth:token-type:access_token" \ --data-urlencode "requested_subject=john.doe" \ http://localhost:8080/auth/realms/swarm/protocol/openid-connect/token
Why this works:
audiencedefines which service the token is intended for (the backend that will validate it)requested_client_idexplicitly tells Keycloak the resulting token should be associated withtarget-client, which sets theazpclaim correctlyrequested_token_typeclarifies you want a standard access token, aligning with your backend validation use case
2. Permission Configuration Clarification
This isn't a Keycloak bug—it's a misunderstanding of which permissions apply to which entities:
admin-impersonating.permission.users: This permission is meant for the impersonating client (yourimpersonator-client). It grants the client permission to initiate user impersonation, which is why your request succeeded when you used this.user-impersonated.permission.users: This permission is meant for individual users (likejohn.doe), not clients. It allows that specific user to be impersonated by authorized clients. Assigning this to a client will be rejected because the permission's target is users, not client entities.
Your current permission setup is actually correct for your use case:
- Grant
admin-impersonating.permission.userstoimpersonator-client(enables it to simulate users) - Grant the token exchange permission (
token-exchange.permission.client.<target-client-uuid>) toimpersonator-client(enables it to exchange tokens fortarget-client)
Just double-check that target-client is configured as a public client (no client secret) and that "Direct Access Grants Enabled" is turned off for it (best practice for public clients).
Additional Checks
- Confirm the
john.doeuser exists in theswarmrealm and has no impersonation restrictions - Enable debug logging for the
org.keycloak.servicespackage in Keycloak if you still encounter issues—logs will reveal any hidden permission or configuration gaps
内容的提问来源于stack exchange,提问作者haiz-apl

