调用Keycloak API持续出现403错误的技术求助
Hey there, let's break down exactly what's going on here and how to fix it:
Why You're Getting a 403
Your access token has the right roles on paper (view-users, query-users), but they're tied to the wrong realm—and that's the root of your problem. Let's break this down:
Your token's roles belong to
mycompany-realm, notmaster
Looking at your token payload, theresource_accesssection only lists roles formycompany-realm. But when you call the master realm's admin API (/auth/admin/realms/master/users), Keycloak checks if you have permissions in the master realm'srealm-managementclient—notmycompany-realm.The
audfield mismatch is a symptom, not the main cause
Your token'saudis set tomycompany-realm, which means it's intended for use with resources in that realm, not the master realm's admin endpoints. This happens because your token request was configured to targetmycompany-realminstead of the master realm's admin tools.
Why Your Token Has the Wrong aud & Roles
When you called the master realm's token endpoint (/auth/realms/master/protocol/openid-connect/token), you likely added an audience=mycompany-realm parameter, or your admin-cli client in the master realm has audience restrictions forcing it to target mycompany-realm. Either way, the token you got is tailored for mycompany-realm operations, not master realm admin tasks.
Fix Steps
1. Fetch a Correct Master Realm Admin Token
Instead of manually calling the token endpoint, let the keycloak-admin library handle auth properly. Use this setup to get a token with master realm admin permissions:
const KeycloakAdminClient = require('keycloak-admin').default; async function initAdminClient() { const kcAdminClient = new KeycloakAdminClient({ baseUrl: 'https://auth-mycompany.com/auth', realmName: 'master', }); await kcAdminClient.auth({ username: 'myname', password: 'your-admin-password', grantType: 'password', clientId: 'admin-cli', }); return kcAdminClient; }
This will automatically fetch a token where:
resource_accessincludes arealm-managemententry with your admin rolesaudis set toadmin-cli(the correct audience for admin operations)
2. Verify Your User Has Master Realm Admin Roles
Double-check in the Keycloak console:
- Go to the master realm →
Users→ Find your user →Role Mappings - Under
Client Roles, selectrealm-management - Ensure roles like
view-users,query-usersare assigned here (not just inmycompany-realm)
3. Fix the admin-cli Client Configuration (If Needed)
If you still get the wrong aud after step 1:
- In the master realm →
Clients→admin-cli→Settings - Scroll to
Advanced Settings→Audience Restrictions - Remove
mycompany-realmfrom this list (or addadmin-cliif it's missing) - Save changes and re-authenticate
Test the Fix
After fetching the new token, decode it to confirm:
resource_access.realm-management.rolesincludes your admin permissionsaudis set toadmin-cli
Then try calling the admin API again—your 403 error should be gone.
内容的提问来源于stack exchange,提问作者Hermine

