Esempio n. 1
0
    def oauthCode(self, csrf_token, session_token):
        """This function is Step2 of the OAUTH2.0 mechanism to get auth code using CSRF token and session key.

        :param csrf_token: CSRF token obtained from Step1 of OAUTH2.0
        :type csrf_token: str
        :param session_token: Session key obtained from Step1 of OAUTH2.0
        :type session_token: str
        :return: Auth code received in the response payload of the API call.
        :rtype: str
        """
        auth_code = None
        path = "/oauth2/authorize/central/api"
        query = {
            "client_id": self.central_info["client_id"],
            "response_type": "code",
            "scope": "all"
        }
        url = get_url(base_url=self.central_info["base_url"],
                      path=path,
                      query=query)

        customer_id = self.central_info["customer_id"]
        data = json.dumps({'customer_id': customer_id}).encode("utf-8")
        headers = {
            'X-CSRF-TOKEN': csrf_token,
            'Content-Type': 'application/json',
            'Cookie': "session=" + session_token
        }
        try:
            s = requests.Session()
            req = requests.Request(method="POST",
                                   url=url,
                                   data=data,
                                   headers=headers)
            prepped = s.prepare_request(req)
            settings = s.merge_environment_settings(prepped.url, {}, None,
                                                    self.ssl_verify, None)
            resp = s.send(prepped, **settings)
            if resp and resp.status_code == 200:
                result = json.loads(resp.text)
                auth_code = result['auth_code']
                return auth_code
            else:
                resp_msg = {"code": resp.status_code, "msg": resp.text}
                self.logger.error(
                    "OAUTH2.0 Step2 obtaining Auth code API call failed with response "
                    + str(resp_msg))
                sys.exit(1)
        except Exception as e:
            self.logger.error("Central Login Step2 failed with error " +
                              str(e))
            sys.exit(1)
Esempio n. 2
0
    def refreshToken(self, old_token):
        """This function refreshes the provided API Gateway token using OAUTH2.0 API. In addition to the input args,
        this function also depends on the class variable definitions client_id and client_secret.

        :param old_token: API Gateway token dict consisting of refresh_token.
        :type old_token: dict
        :raises UserWarning: Raises warning when validation of availability of the required parameters fails.
        :raises UserWarning: Raises warning when token input param is provided but it doesn't have refresh_token.
        :return: Token dictionary consisting of refreshed access_token and new refresh_token.
        :rtype: dict
        """
        token = None
        resp = ''
        try:
            if not self.validateRefreshTokenParams():
                raise UserWarning("")
            if "refresh_token" not in old_token:
                raise UserWarning("refresh_token not present in the input "
                                  "token dict")

            path = "/oauth2/token"
            query = {
                "client_id": self.central_info["client_id"],
                "client_secret": self.central_info["client_secret"],
                "grant_type": "refresh_token",
                "refresh_token": old_token["refresh_token"]
            }
            url = get_url(base_url=self.central_info["base_url"],
                          path=path,
                          query=query)

            s = requests.Session()
            req = requests.Request(method="POST", url=url)
            prepped = s.prepare_request(req)
            settings = s.merge_environment_settings(prepped.url, {}, None,
                                                    self.ssl_verify, None)
            resp = s.send(prepped, **settings)
            if resp.status_code == 200:
                token = json.loads(resp.text)
            else:
                resp_msg = {"code": resp.status_code, "msg": resp.text}
                self.logger.error(
                    "Refresh token API call failed with response " +
                    str(resp_msg))
        except Exception as err:
            self.logger.error("Unable to refresh token.. " "%s" % str(err))
        return token
Esempio n. 3
0
    def oauthLogin(self):
        """This function is Step1 of the OAUTH2.0 mechanism to generate access token. Login to Aruba Central
        is performed using username and password.

        :return: Tuple with two strings, csrf token and login session key.
        :rtype: tuple
        """
        headers = {'Content-Type': 'application/json'}

        path = "/oauth2/authorize/central/api/login"
        query = {"client_id": self.central_info["client_id"]}
        url = get_url(base_url=self.central_info["base_url"],
                      path=path,
                      query=query)

        data = json.dumps({
            "username": self.central_info["username"],
            "password": self.central_info["password"]
        })
        data = data.encode("utf-8")
        try:
            s = requests.Session()
            req = requests.Request(method="POST",
                                   url=url,
                                   data=data,
                                   headers=headers)
            prepped = s.prepare_request(req)
            settings = s.merge_environment_settings(prepped.url, {}, None,
                                                    self.ssl_verify, None)
            resp = s.send(prepped, **settings)
            if resp and resp.status_code == 200:
                cookies = resp.cookies.get_dict()
                return cookies['csrftoken'], cookies['session']
            else:
                resp_msg = {"code": resp.status_code, "msg": resp.text}
                self.logger.error(
                    "OAUTH2.0 Step1 login API call failed with response " +
                    str(resp_msg))
                sys.exit(1)
        except Exception as e:
            self.logger.error("OAUTH2.0 Step1 failed with error " + str(e))
            sys.exit(1)
Esempio n. 4
0
    def oauthAccessToken(self, auth_code):
        """This function is Step3 of the OAUTH2.0 mechanism to generate API access token.

        :param auth_code: Auth code from Step2 of OAUTH2.0.
        :type auth_code: str
        :return: token information received from API call consisting of access_token and refresh_token.
        :rtype: dict
        """
        path = "/oauth2/token"
        query = {
            "client_id": self.central_info["client_id"],
            "client_secret": self.central_info["client_secret"],
            "grant_type": "authorization_code",
            "code": auth_code
        }
        url = get_url(base_url=self.central_info["base_url"],
                      path=path,
                      query=query)

        try:
            s = requests.Session()
            req = requests.Request(method="POST", url=url)
            prepped = s.prepare_request(req)
            settings = s.merge_environment_settings(prepped.url, {}, None,
                                                    self.ssl_verify, None)
            resp = s.send(prepped, **settings)
            if resp.status_code == 200:
                result = json.loads(resp.text)
                token = result
                return token
            else:
                resp_msg = {"code": resp.status_code, "msg": resp.text}
                self.logger.error(
                    "OAUTH2.0 Step3 creating access token API call failed with response "
                    + str(resp_msg))
                sys.exit(1)
        except Exception as e:
            self.logger.error("Central Login Step3 failed with error " +
                              str(e))
            sys.exit(1)
Esempio n. 5
0
    def command(self,
                apiMethod,
                apiPath,
                apiData={},
                apiParams={},
                headers={},
                files={},
                retry_api_call=True):
        """This function calls requestURL to make an API call to Aruba Central after gathering parameters required for API call.
        When an API call fails with HTTP 401 error code, the same API call is retried once after an attempt to refresh access token or
        create new access token is made.

        :param apiMethod: HTTP Method for API call. Should be one of the supported methods for the respective Aruba Central API endpoint.
        :type apiMethod: str
        :param apiPath: Path to the API endpoint as required by API endpoint. Refer Aruba Central API reference swagger documentation.
        :type apiPath: str
        :param apiData: HTTP payload for the API call as required by API endpoint. Refer Aruba Central API reference swagger
            documentation, defaults to {}
        :type apiData: dict, optional
        :param apiParams: HTTP url query parameters as required by API endpoint. Refer Aruba Central API reference
            swagger, defaults to {}
        :type apiParams: dict, optional
        :param headers: HTTP headers as required by API endpoint. Refer Aruba Central API reference swagger, defaults to {}
        :type headers: dict, optional
        :param files: Some API endpoints require a file upload instead of apiData. Provide file data in the format accepted by API
            endpoint and Python requests library, defaults to {}
        :type files: dict, optional
        :param retry_api_call: Attempts to refresh api token and retry the api call when invalid token error is received, defaults to True
        :type retry_api_call: bool, optional
        :return: HTTP response with HTTP staus_code and HTTP response payload. \n
            * keyword code: HTTP status code \n
            * keyword msg: HTTP response payload \n
        :rtype: dict
        """
        retry = 0
        result = ''
        method = apiMethod
        while retry <= 1:
            if not retry_api_call:
                retry = 100
            url = get_url(self.central_info["base_url"],
                          apiPath,
                          query=apiParams)
            if not headers and not files:
                headers = {
                    "Content-Type": "application/json",
                    "Accept": "application/json"
                }
            if apiData and headers['Content-Type'] == "application/json":
                apiData = json.dumps(apiData)

            resp = self.requestUrl(url=url,
                                   data=apiData,
                                   method=method,
                                   headers=headers,
                                   params=apiParams,
                                   files=files)
            try:
                if resp.status_code == 401 and "invalid_token" in resp.text and retry_api_call:
                    self.logger.error("Received error 401 on requesting url "
                                      "%s with resp %s" %
                                      (str(url), str(resp.text)))
                    if retry < 1:
                        self.handleTokenExpiry()
                    retry += 1
                else:
                    result = {"code": resp.status_code, "msg": resp.text}
                    try:
                        result["msg"] = json.loads(result["msg"])
                    except:
                        pass
                    return result
            except Exception as err:
                self.logger.error(err)
                exit("exiting...")