Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Keycloak Get Roles and Groups of user

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 protected]'
}

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

like image 362
sudhanshu Avatar asked Sep 02 '25 09:09

sudhanshu


1 Answers

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".

like image 90
Marcos Pereira Júnior Avatar answered Sep 04 '25 21:09

Marcos Pereira Júnior