2

Using Key Cloak created groups and assigned roles to the groups. Than created the users and assigned the users to specific groups.

To access all this in my application I am using Python-Keycloak

As mentioned in github doc, using following code to access the user information.

from keycloak import KeycloakOpenID

keycloak_openid = KeycloakOpenID(server_url="http://localhost:8080/auth/",
                    client_id="account",
                    realm_name="demo",
                    client_secret_key="my_secret_key")

config_well_know = keycloak_openid.well_know()

token = keycloak_openid.token("username", "password")
userinfo = keycloak_openid.userinfo(token['access_token'])

Getting following userinfo

{
    'family_name': 'Lastname', 
    'preferred_username': 'user_name', 
    'sub': 'some_key', 
    'given_name': 'Fistname', 
    'name': 'Firstname Lastname', 
    'email': 'email@example.com'
}

How can I access the group and roles information of the user.

sudhanshu
  • 423
  • 1
  • 9
  • 23

5 Answers5

8

You need to use "KeycloakAdmin" class in the same library (python-keycloak):

from keycloak import KeycloakAdmin

admin = KeycloakAdmin(server_url='https://server-url',
                      username='username',
                      password='password',
                      realm_name='realm',
                      verify=True)

user_groups = admin.get_user_groups(user_id="user-id")

For use KeycloakAdmin, you will need of a user with access to "admin-cli".

  • This dies trying to get token (with my credentials, of course): `/usr/local/lib/python3.6/site-packages/keycloak/keycloak_admin.py in __init__ self.get_token() … Local vars /usr/local/lib/python3.6/site-packages/keycloak/keycloak_admin.py in get_token self._token = self.keycloak_openid.token(self.username, self.password, grant_type=grant_type) … Local vars /usr/local/lib/python3.6/site-packages/keycloak/keycloak_openid.py in token return raise_error_from_response(data_raw, KeycloakGetError) ` – SwissNavy Jan 21 '20 at 16:53
  • And with backslash at the end of server_url it gives this error: `Exception Value: 401: b'{"error":"invalid_grant","error_description":"Invalid user credentials"}'`. My user is admin – SwissNavy Jan 21 '20 at 17:34
  • you need to config the client key, 1. make sure "Service Accounts Enabled" 2. assign client roles to it -> realm-management client role -> view-users – dameng Apr 24 '20 at 03:57
7
  1. Go to Keycloak, select you client -> Mapper -> Create.
  2. In a Mapper Type list select "Group Membership".
  3. In Token Claim Name field specify desired userinfo property name, e.g. "Groups".
  4. In Name field specify whatever you want for mapper name and click Save.
  5. Try again authenticating to Keycloak with your app. User groups should now be visible in userinfo JSON.
Vasili Angapov
  • 8,061
  • 15
  • 31
  • Interesting solution. So this is essentially adding custom fields to the 'userinfo' response object with role, or group, or other available info. Am I understanding correctly? – pedorro Sep 06 '19 at 17:48
  • @Vasily Angapov Where is the value "Groups" for Token Claim Name field came from? I am trying to figure out what would be the equivalent of it for social-auth-app-django package. – SwissNavy Jan 23 '20 at 12:29
  • 2
    This should be the selected answer. Cleanest of them all. – HyperionX Jun 11 '21 at 01:35
2

Created one admin user for my realm. and inherit the class like this

from keycloak import KeycloakAdmin
from keycloak.exceptions import raise_error_from_response, KeycloakGetError

class CustomKeycloakAdmin(KeycloakAdmin):
    def get_user_group(self,user_name):
        USER_GROUP_URL = "admin/realms/{realm-name}/users/{user-id}/groups"
        params_path = {"user-id":self.get_user_id(user_name),"realm-name": self.realm_name}
        data_raw = self.connection.raw_get(USER_GROUP_URL.format(**params_path))
        return raise_error_from_response(data_raw, KeycloakGetError)

if __name__=="__main__":
    keycloak_admin = CustomKeycloakAdmin(server_url="http://localhost:8080/auth/",username='admin_user',password='admin_password',realm_name="my_realm",verify=True)
    user_group = keycloak_admin.get_user_group("user_name")
sudhanshu
  • 423
  • 1
  • 9
  • 23
0

I think we have to set the realm or client role in Keycloak for the user. Once you set you will automatically get the role details in ‘user_groups ‘

Cheers SG

Sumesh S.G
  • 43
  • 1
  • 6
0

You can also use the keycloak API's to retrieve the particular user Group and Role details

Example CURL to get the Group details: GET /{realm}/users/{id}/groups

curl 'http://keycloak.local:8000/auth/admin/realms/master/groups?first=0&max=20' \
  -H 'Connection: keep-alive' \
  -H 'Accept: application/json, text/plain, */*' \
  -H 'Authorization: Bearer <access_token>' \
  --compressed \
  --insecure

You can refer to the keycloak official documentation for the Users API keycloak Website

Akshay Jain
  • 790
  • 1
  • 7
  • 21