使用
401: b'{"error":"invalid_grant","error_description":"Invalid user credentials"}'
功能将领域从“master”切换到“new-sso”领域后,出现 change_current_realm()
错误。
完整代码如下:
from keycloak import KeycloakAdmin
from keycloak import KeycloakOpenIDConnection
server_url = "http://localhost:8080/"
new_sso_relam = "new-sso"
admin_username = 'admin'
admin_password = 'admin'
admin_client = 'admin-cli'
master_realm = "master"
keycloak_connection = KeycloakOpenIDConnection(server_url=server_url,
username=admin_username,
password=admin_password,
client_id=admin_client,
realm_name=master_realm)
keycloak_admin = KeycloakAdmin(connection=keycloak_connection)
keycloak_admin.change_current_realm(new_sso_relam)
user_payload = {"username": "new_user",
"enabled": True}
keycloak_admin.create_user(user_payload, exist_ok=True)
但是,如果在切换到“新领域”之前我调用
keycloak_admin.get_realm(master_realm)
,那么代码可以正常工作,我可以创建用户。
keycloak_admin.get_realm(master_realm)
keycloak_admin.change_current_realm(new_sso_relam)
user_payload = {"username": "new_user",
"enabled": True}
keycloak_admin.create_user(user_payload, exist_ok=True)
我相信
invalid_grant
错误表明在使用 change_current_realm()
切换领域后,我使用的凭据对于新领域不再有效。出现此问题的原因是 Keycloak 管理客户端(在本例中为 admin-cli
)针对“master”领域进行了身份验证,并且不会自动将这些凭据转移到“new-sso”领域。
当我拨打
keycloak_admin.get_realm(master_realm)
时,它似乎会刷新或验证您的会话,让您成功切换到新领域。但是,您想消除这个额外的步骤。
您需要在KeycloakOpenIDConnection()中添加
user_realm_name=master_realm
keycloak_connection = KeycloakOpenIDConnection(server_url=server_url,
username=admin_username,
password=admin_password,
client_id=admin_client,
realm_name=master_realm,
user_realm_name=master_realm)
docker-compose 在这里
new-sso
领域new-sso
create-user.py
from keycloak import KeycloakOpenIDConnection, KeycloakAdmin
server_url = "http://localhost:8080/"
new_sso_relam = "new-sso"
admin_username = 'admin'
admin_password = 'admin'
admin_client = 'admin-cli'
master_realm = "master"
keycloak_connection = KeycloakOpenIDConnection(server_url=server_url,
username=admin_username,
password=admin_password,
client_id=admin_client,
realm_name=master_realm,
user_realm_name=master_realm)
keycloak_admin = KeycloakAdmin(connection=keycloak_connection)
keycloak_admin.change_current_realm(new_sso_relam)
user_payload = {"username": "new_user","enabled": True}
keycloak_admin.create_user(user_payload, exist_ok=True)
print("new_user registered")
pip install python-keycloak