From d6a39c71761ab5e8b6acf74e9a771c0d68714cd5 Mon Sep 17 00:00:00 2001 From: Martyn Klassen Date: Wed, 15 Mar 2023 17:05:35 -0400 Subject: [PATCH] feat: Add client update method --- src/keycloak/keycloak_openid.py | 30 ++++++++++++++++++++++++++++++ tests/test_keycloak_admin.py | 6 +++++- 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/src/keycloak/keycloak_openid.py b/src/keycloak/keycloak_openid.py index f689c37..2503077 100644 --- a/src/keycloak/keycloak_openid.py +++ b/src/keycloak/keycloak_openid.py @@ -41,6 +41,7 @@ from .exceptions import ( KeycloakGetError, KeycloakInvalidTokenError, KeycloakPostError, + KeycloakPutError, KeycloakRPTNotFound, raise_error_from_response, ) @@ -49,6 +50,7 @@ from .urls_patterns import ( URL_AUTH, URL_CERTS, URL_CLIENT_REGISTRATION, + URL_CLIENT_UPDATE, URL_ENTITLEMENT, URL_INTROSPECT, URL_LOGOUT, @@ -711,3 +713,31 @@ class KeycloakOpenID: URL_CLIENT_REGISTRATION.format(**params_path), data=json.dumps(payload) ) return raise_error_from_response(data_raw, KeycloakPostError) + + def update_client(self, token: str, client_id: str, payload: dict): + """Update a client. + + ClientRepresentation: + https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation + + :param token: registration access token + :type token: str + :param client_id: Keycloak client id + :type client_id: str + :param payload: ClientRepresentation + :type payload: dict + :return: Client Representation + :rtype: dict + """ + params_path = {"realm-name": self.realm_name, "client-id": client_id} + self.connection.add_param_headers("Authorization", "Bearer " + token) + self.connection.add_param_headers("Content-Type", "application/json") + + # Keycloak complains if the clientId is not set in the payload + if "clientId" not in payload: + payload["clientId"] = client_id + + data_raw = self.connection.raw_put( + URL_CLIENT_UPDATE.format(**params_path), data=json.dumps(payload) + ) + return raise_error_from_response(data_raw, KeycloakPutError) diff --git a/tests/test_keycloak_admin.py b/tests/test_keycloak_admin.py index eec3a28..6ac69bb 100644 --- a/tests/test_keycloak_admin.py +++ b/tests/test_keycloak_admin.py @@ -2748,7 +2748,7 @@ def test_initial_access_token( res = oid.register_client( token=res["token"], payload={ - "name": client, + "name": "DynamicRegisteredClient", "clientId": client, "enabled": True, "publicClient": False, @@ -2758,3 +2758,7 @@ def test_initial_access_token( }, ) assert res["clientId"] == client + + new_secret = str(uuid.uuid4()) + res = oid.update_client(res["registrationAccessToken"], client, payload={"secret": new_secret}) + assert res["secret"] == new_secret