Keycloak Get Users returns 403 forbidden

Viewed 11399

I create token using http://localhost:8080/auth/realms/{realm_name}/protocol/openid-connect/token endpoint.

grant_type=client_credentials
client-id: ------------
client-secret: 78296d38-cc82-4010-a817-65c283484e51

Now I want to get users of realm. Then I send request to http://localhost:8080/auth/admin/realms/{realm_name}/users?username=demo endpoint with token. But I got 403 forbidden response with "error": "unknown_error". How to solve it?

2 Answers

The service account associated with your client needs to be allowed to view the realm users.

  1. Go to http://localhost:8080/auth/admin/{realm_name}/console/#/realms/{realm_name}/clients

  2. Select your client (which must be a confidential client)

  3. In the settings tab, switch Service Account Enabled to ON

  4. Click on save, the Service Account Roles tab will appear

  5. In Client Roles, select realm_management

  6. Scroll through available roles until you can select view_users

  7. Click on Add selected

You should have something like this :

enter image description here

You client is now allowed to access users through the REST API.

I ran into the same issue with the quarkus-Version 18.0.2:

  • a client "tmp" identical configured like "admin-cli" (only different name)
  • all roles of "realm-management" assigned to the generated service-user
  • using a client-credential-Token of "tmp" for the user-Search-Endpoint (/auth/admin/realms/b2c/users/) leads to 403
  • using a manually created user works well (password-credential-type)
  • using the "admin-cli" client to get the client-credential-Token works well, too

I found this: "client_id is a confidential client that belongs to the realm master" here: https://github.com/keycloak/keycloak-documentation/blob/main/server_development/topics/admin-rest-api.adoc

I don't know why this restriction was introduced, but when you fetch your token from master (/auth/realms/master/protocol/openid-connect/token), then you are allowed to use a custom client and everything is fine.

Related