Beispiel #1
0
 def retrieve_keycloak_token(self):
     if self.keycloak_config.client_mode in trueValues:
         params = {
             'grant_type': 'client_credentials',
             'client_id': self.keycloak_config.client_id,
             'client_secret': self.keycloak_config.client_secret,
         }
         r = requests.post(self.keycloak_config.url, params, verify=False)
         if r.status_code == 200:
             logging.info("Token retrieved for client from {}.\n".format(
                 self.keycloak_config.client_id))
             self.access_token_time = utils.current_time_millis()
             self.refresh_token_time = utils.current_time_millis()
             reply = json.loads(r.content.decode('utf-8'))
             self.refresh_token = str(reply.get('refresh_token'))
             self.access_token = str(reply.get('access_token'))
         else:
             logging.error("Failed to retrieve client token:")
             logging.error(r)
             logging.error(r.content)
             exit(1)
     else:
         if self.username and self.password:
             params = {
                 'grant_type': 'password',
                 'client_id': self.keycloak_config.client_id,
                 'username': self.username,
                 'password': self.password
             }
             r = requests.post(self.keycloak_config.url,
                               params,
                               verify=False)
             if r.status_code == 200:
                 logging.info("Token retrieved for {}.\n".format(
                     self.username))
                 self.access_token_time = utils.current_time_millis()
                 self.refresh_token_time = utils.current_time_millis()
                 reply = json.loads(r.content.decode('utf-8'))
                 self.refresh_token = str(reply.get('refresh_token'))
                 self.access_token = str(reply.get('access_token'))
             else:
                 logging.error("Failed to retrieve token:")
                 logging.error(r)
                 logging.error(r.content)
                 exit(1)
         else:
             logging.error(
                 "No credentials. Authentication is not possible.")
Beispiel #2
0
    def __setstate__(self, state):
        # here we need to read the config file again, to check that values for URLs haven't changed. the way to
        # change the username / password will be a login function the user calls. ideally the config file won't need
        # to be changed much once it's in place
        newtoken = False
        config = utils.get_config()
        saved_kc_config, saved_username, self.token, self.token_time = state
        self.pnc_config = psc.PncServerConfig(config)

        # check for changes in keycloak usrname; if so, we'll need to get a new token regardless of time
        self.username = self.load_username_from_config(config)
        if self.username is not None and self.username != saved_username:
            sys.stderr.write(
                "Keycloak username has been changed. Retrieving new token...\n"
            )
            newtoken = True
        else:
            self.username = saved_username

        # check for changes in keycloak configuration; if so, we'll need to get a new token regardless of time
        current_keycloak_config = kc.KeycloakConfig(config)
        if not current_keycloak_config == saved_kc_config:
            logging.info(
                "Keycloak server has been reconfigured. Retrieving new token...\n"
            )
            self.keycloak_config = current_keycloak_config
            newtoken = True
        else:
            self.keycloak_config = saved_kc_config

        # if more than a day has passed since we saved the token, and keycloak server configuration is not modified,
        # get a new one
        if not newtoken and utils.current_time_millis(
        ) - self.token_time > 86400000:
            # input the password again since we no longer cache it
            logging.info(
                "Keycloak token has expired for user {}. Retrieving new token...\n"
                .format(self.username))
            newtoken = True

        if newtoken:
            # if using client auth, we simply get a new token.
            if (self.keycloak_config.client_mode in ['True', 'true', '1']):
                self.token = self.retrieve_keycloak_token()
            else:
                # enter password to get new token, but only if the user has not entered a password in pnc-cli.conf
                password = self.load_password_from_config(config)
                if password:
                    self.password = password
                else:
                    self.password = self.input_password()
                self.token = self.retrieve_keycloak_token()
        self.apiclient = self.create_api_client()
Beispiel #3
0
 def retrieve_keycloak_token(self):
     if self.keycloak_config.client_mode in trueValues:
         params = {'grant_type': 'client_credentials',
                   'client_id': self.keycloak_config.client_id,
                   'client_secret': self.keycloak_config.client_secret,
         }
         r = requests.post(self.keycloak_config.url, params, verify=False)
         if r.status_code == 200:
             logging.info("Token retrieved for client from {}.\n".format(self.keycloak_config.client_id))
             self.access_token_time = utils.current_time_millis()
             self.refresh_token_time = utils.current_time_millis()
             reply = json.loads(r.content.decode('utf-8'))
             self.refresh_token = str(reply.get('refresh_token'))
             self.access_token = str(reply.get('access_token'))
         else:
             logging.error("Failed to retrieve client token:")
             logging.error(r)
             logging.error(r.content)
             exit(1)
     else:
         if self.username and self.password:
             params = {'grant_type': 'password',
                       'client_id': self.keycloak_config.client_id,
                       'username': self.username,
                       'password': self.password}
             r = requests.post(self.keycloak_config.url, params, verify=False)
             if r.status_code == 200:
                 logging.info("Token retrieved for {}.\n".format(self.username))
                 self.access_token_time = utils.current_time_millis()
                 self.refresh_token_time = utils.current_time_millis()
                 reply = json.loads(r.content.decode('utf-8'))
                 self.refresh_token = str(reply.get('refresh_token'))
                 self.access_token = str(reply.get('access_token'))
             else:
                 logging.error("Failed to retrieve token:")
                 logging.error(r)
                 logging.error(r.content)
                 exit(1)
         else:
             logging.error("No credentials. Authentication is not possible.")
Beispiel #4
0
 def refresh_access_token(self):
     params = {'grant_type': 'refresh_token',
               'client_id': self.keycloak_config.client_id,
               'refresh_token': self.refresh_token
               }
     r = requests.post(self.keycloak_config.url,params,verify=False)
     if r.status_code == 200:
         if self.username:
             logging.info("Token refreshed for user {}. \n".format(self.username))
         else:
             logging.info("Token refreshed for client from {}. \n".format(self.keycloak_config.client_id))
         self.access_token_time = utils.current_time_millis()
         reply = json.loads(r.content.decode('utf-8'))
         self.access_token = str(reply.get('access_token'))
Beispiel #5
0
 def refresh_access_token(self):
     params = {'grant_type': 'refresh_token',
               'client_id': self.keycloak_config.client_id,
               'refresh_token': self.refresh_token
               }
     r = requests.post(self.keycloak_config.url,params,verify=False)
     if r.status_code == 200:
         if self.username:
             logging.info("Token refreshed for user {}. \n".format(self.username))
         else:
             logging.info("Token refreshed for client from {}. \n".format(self.keycloak_config.client_id))
         self.access_token_time = utils.current_time_millis()
         reply = json.loads(r.content.decode('utf-8'))
         self.access_token = str(reply.get('access_token'))
Beispiel #6
0
 def retrieve_keycloak_token(self):
     if self.username and self.password:
         params = {
             'grant_type': 'password',
             'client_id': self.keycloak_config.client_id,
             'username': self.username,
             'password': self.password
         }
         r = requests.post(self.keycloak_config.url, params, verify=False)
         if r.status_code == 200:
             print("Token retrieved for {}.".format(self.username))
             self.token_time = utils.current_time_millis()
             reply = json.loads(r.content.decode('utf-8'))
             return str(reply.get('access_token'))
         else:
             print("Failed to retrieve token:")
             print(r)
             print(r.content)
             exit(1)
     else:
         print("No credentials. Authentication is not possible.")
Beispiel #7
0
    def __setstate__(self, state):
        # here we need to read the config file again, to check that values for URLs haven't changed. the way to
        # change the username / password will be a login function the user calls. ideally the config file won't need
        # to be changed much once it's in place
        newtoken = False
        refreshtoken = False
        config, configFileName = utils.get_config()
        self.configFileName = configFileName

        if len(state) == 4:
            # old version of saved user_config
            saved_kc_config, saved_username, self.access_token, self.access_token_time = state
            self.refresh_token_time = 0
            refreshtoken = True
        else:
            saved_kc_config, saved_username, self.access_token, self.access_token_time, self.refresh_token, self.refresh_token_time = state

        self.pnc_config = psc.PncServerConfig(config)

        # check for changes in keycloak username; if so, we'll need to get a new token regardless of time
        self.username = self.load_username_from_config(config)
        if self.username is not None and self.username != saved_username:
            sys.stderr.write("Keycloak username has been changed. Retrieving new token...\n")
            newtoken = True
        else:
            self.username = saved_username

        # check for changes in keycloak configuration; if so, we'll need to get a new token regardless of time
        current_keycloak_config = kc.KeycloakConfig(config)
        if not current_keycloak_config == saved_kc_config:
            logging.info("Keycloak server has been reconfigured. Retrieving new token...\n")
            self.keycloak_config = current_keycloak_config
            newtoken = True
        else:
            self.keycloak_config = saved_kc_config


        # if more than a day has passed since we saved the token, and keycloak server configuration is not modified,
        # get a new one
        if not newtoken and utils.current_time_millis() - self.refresh_token_time >= 8640000:
            # input the password again since we no longer cache it
            logging.info("Keycloak token has expired for user {}. Retrieving new token...\n".format(self.username))
            newtoken = True

        # if access_token is more than hour old, refresh it
        if not newtoken and 8640000 >= utils.current_time_millis() - self.access_token_time > 360000:
            logging.info("Refreshing access token for user {}. \n".format(self.username))
            refreshtoken = True

        if not newtoken and refreshtoken:
            self.refresh_access_token()

        if newtoken:
            # if using client auth, we simply get a new token.
            if self.keycloak_config.client_mode in trueValues:
                self.retrieve_keycloak_token()
            else:
                # enter password to get new token, but only if the user has not entered a password in pnc-cli.conf
                password = self.load_password_from_config(config)
                if password:
                    self.password = password
                else:
                    self.password = self.input_password()
                self.retrieve_keycloak_token()
        self.apiclient = self.create_api_client()