From a6ad87d62c62bc3ab7bac5bf1ebd935a3a314488 Mon Sep 17 00:00:00 2001 From: robsonyeg Date: Wed, 17 Nov 2021 14:51:37 -0700 Subject: [PATCH] fix invalid credential error and refresh_code not exist error --- keycloak/keycloak_admin.py | 31 +++++++++++++++++++++---------- 1 file changed, 21 insertions(+), 10 deletions(-) diff --git a/keycloak/keycloak_admin.py b/keycloak/keycloak_admin.py index f567be1..5dad457 100644 --- a/keycloak/keycloak_admin.py +++ b/keycloak/keycloak_admin.py @@ -1873,7 +1873,14 @@ class KeycloakAdmin: return r def get_token(self): - token_realm_name = 'master' if self.client_secret_key else self.user_realm_name or self.realm_name + # token_realm_name = 'master' if self.client_secret_key else self.user_realm_name or self.realm_name + if self.user_realm_name: + token_realm_name = self.user_realm_name + elif self.realm_name: + token_realm_name = self.realm_name + else: + token_realm_name = "master" + self.keycloak_openid = KeycloakOpenID(server_url=self.server_url, client_id=self.client_id, realm_name=token_realm_name, verify=self.verify, client_secret_key=self.client_secret_key, @@ -1902,15 +1909,19 @@ class KeycloakAdmin: verify=self.verify) def refresh_token(self): - refresh_token = self.token.get('refresh_token') - try: - self.token = self.keycloak_openid.refresh_token(refresh_token) - except KeycloakGetError as e: - if e.response_code == 400 and (b'Refresh token expired' in e.response_body or - b'Token is not active' in e.response_body): - self.get_token() - else: - raise + refresh_token = self.token.get('refresh_token', None) + if refresh_token is None: + self.get_token() + else: + try: + self.token = self.keycloak_openid.refresh_token(refresh_token) + except KeycloakGetError as e: + if e.response_code == 400 and (b'Refresh token expired' in e.response_body or + b'Token is not active' in e.response_body): + self.get_token() + else: + raise + self.connection.add_param_headers('Authorization', 'Bearer ' + self.token.get('access_token')) def get_client_all_sessions(self, client_id):