Пример #1
0
    def test_request_body(self):
        client = LegacyApplicationClient(self.client_id)

        # Basic, no extra arguments
        body = client.prepare_request_body(self.username, self.password,
                body=self.body)
        self.assertFormBodyEqual(body, self.body_up)

        # With extra parameters
        body = client.prepare_request_body(self.username, self.password,
                body=self.body, **self.kwargs)
        self.assertFormBodyEqual(body, self.body_kwargs)
Пример #2
0
    def test_request_body(self):
        client = LegacyApplicationClient(self.client_id)

        # Basic, no extra arguments
        body = client.prepare_request_body(self.username, self.password,
                body=self.body)
        self.assertFormBodyEqual(body, self.body_up)

        # With extra parameters
        body = client.prepare_request_body(self.username, self.password,
                body=self.body, **self.kwargs)
        self.assertFormBodyEqual(body, self.body_kwargs)
Пример #3
0
    def test_prepare_request_body(self):
        """
        see issue #585
            https://github.com/oauthlib/oauthlib/issues/585
        """
        client = LegacyApplicationClient(self.client_id)

        # scenario 1, default behavior to not include `client_id`
        r1 = client.prepare_request_body(username=self.username, password=self.password)
        self.assertIn(r1, ('grant_type=password&username=%s&password=%s' % (self.username, self.password, ),
                           'grant_type=password&password=%s&username=%s' % (self.password, self.username, ),
                          ))

        # scenario 2, include `client_id` in the body
        r2 = client.prepare_request_body(username=self.username, password=self.password, include_client_id=True)
        r2_params = dict(urlparse.parse_qsl(r2, keep_blank_values=True))
        self.assertEqual(len(r2_params.keys()), 4)
        self.assertEqual(r2_params['grant_type'], 'password')
        self.assertEqual(r2_params['username'], self.username)
        self.assertEqual(r2_params['password'], self.password)
        self.assertEqual(r2_params['client_id'], self.client_id)

        # scenario 3, include `client_id` + `client_secret` in the body
        r3 = client.prepare_request_body(username=self.username, password=self.password, include_client_id=True, client_secret=self.client_secret)
        r3_params = dict(urlparse.parse_qsl(r3, keep_blank_values=True))
        self.assertEqual(len(r3_params.keys()), 5)
        self.assertEqual(r3_params['grant_type'], 'password')
        self.assertEqual(r3_params['username'], self.username)
        self.assertEqual(r3_params['password'], self.password)
        self.assertEqual(r3_params['client_id'], self.client_id)
        self.assertEqual(r3_params['client_secret'], self.client_secret)

        # scenario 4, `client_secret` is an empty string
        r4 = client.prepare_request_body(username=self.username, password=self.password, include_client_id=True, client_secret='')
        r4_params = dict(urlparse.parse_qsl(r4, keep_blank_values=True))
        self.assertEqual(len(r4_params.keys()), 5)
        self.assertEqual(r4_params['grant_type'], 'password')
        self.assertEqual(r4_params['username'], self.username)
        self.assertEqual(r4_params['password'], self.password)
        self.assertEqual(r4_params['client_id'], self.client_id)
        self.assertEqual(r4_params['client_secret'], '')

        # scenario 4b`,` client_secret is `None`
        r4b = client.prepare_request_body(username=self.username, password=self.password, include_client_id=True, client_secret=None)
        r4b_params = dict(urlparse.parse_qsl(r4b, keep_blank_values=True))
        self.assertEqual(len(r4b_params.keys()), 4)
        self.assertEqual(r4b_params['grant_type'], 'password')
        self.assertEqual(r4b_params['username'], self.username)
        self.assertEqual(r4b_params['password'], self.password)
        self.assertEqual(r4b_params['client_id'], self.client_id)
Пример #4
0
class myOAuth(OAuth):
    def __init__(self, app=None):
        super(myOAuth, self).__init__(app)
        self.app = app
        self.soovii = None

    def init_app(self, app):
        super(myOAuth, self).init_app(app)
        self.soovii = self.remote_app(
            'soovii',
            consumer_key=get_syscfg_val(1),  # 平台ID 企业中心提供
            consumer_secret=get_syscfg_val(2),  # 平台密码 企业中心提供
            request_token_params={},
            base_url=get_syscfg_val(15) + ":" + get_syscfg_val(6),  # 接口地址
            request_token_url=None,
            access_token_method='POST',
            access_token_url=get_syscfg_val(15) + ":" + get_syscfg_val(6) +
            get_syscfg_val(3),  # 登录接口url
            authorize_url=get_syscfg_val(15) + ":" + get_syscfg_val(6) +
            get_syscfg_val(7)  # 刷新token
        )

        self.api_client = LegacyApplicationClient(self.soovii.consumer_key)
        self.soovii.tokengetter(self.get_access_token)

    def get_access_token(self):
        if (not hasattr(current_app, "token")):
            client_credential = (
                "%s:%s" %
                (self.soovii.consumer_key, self.soovii.consumer_secret))
            headers = {
                "Authorization":
                "Basic " +
                to_unicode(base64.encodestring(
                    to_bytes(client_credential))).replace("\n", "")
            }
            body = self.api_client.prepare_request_body(
                get_syscfg_val(8),
                get_syscfg_val(9))  # 对于网址类型的型的项目用户名密码,随意填写,如"soovii", "soovii"

            resp, content = self.soovii.http_request(
                self.soovii.access_token_url,
                headers,
                to_bytes(body),
                method="POST")
            if resp.code not in (200, 201):
                logger.info('Invalid response')
            else:
                dic = json.loads(to_unicode(content))
                current_app.token = dic
                return dic
        else:
            return current_app.token
Пример #5
0
    def test_prepare_request_body(self):
        """
        see issue #585
            https://github.com/oauthlib/oauthlib/issues/585
        """
        client = LegacyApplicationClient(self.client_id)

        # scenario 1, default behavior to not include `client_id`
        r1 = client.prepare_request_body(username=self.username,
                                         password=self.password)
        self.assertIn(r1, (
            'grant_type=password&username={}&password={}'.format(
                self.username, self.password),
            'grant_type=password&password={}&username={}'.format(
                self.password, self.username),
        ))

        # scenario 2, include `client_id` in the body
        r2 = client.prepare_request_body(username=self.username,
                                         password=self.password,
                                         include_client_id=True)
        r2_params = dict(urlparse.parse_qsl(r2, keep_blank_values=True))
        self.assertEqual(len(r2_params.keys()), 4)
        self.assertEqual(r2_params['grant_type'], 'password')
        self.assertEqual(r2_params['username'], self.username)
        self.assertEqual(r2_params['password'], self.password)
        self.assertEqual(r2_params['client_id'], self.client_id)

        # scenario 3, include `client_id` + `client_secret` in the body
        r3 = client.prepare_request_body(username=self.username,
                                         password=self.password,
                                         include_client_id=True,
                                         client_secret=self.client_secret)
        r3_params = dict(urlparse.parse_qsl(r3, keep_blank_values=True))
        self.assertEqual(len(r3_params.keys()), 5)
        self.assertEqual(r3_params['grant_type'], 'password')
        self.assertEqual(r3_params['username'], self.username)
        self.assertEqual(r3_params['password'], self.password)
        self.assertEqual(r3_params['client_id'], self.client_id)
        self.assertEqual(r3_params['client_secret'], self.client_secret)

        # scenario 4, `client_secret` is an empty string
        r4 = client.prepare_request_body(username=self.username,
                                         password=self.password,
                                         include_client_id=True,
                                         client_secret='')
        r4_params = dict(urlparse.parse_qsl(r4, keep_blank_values=True))
        self.assertEqual(len(r4_params.keys()), 5)
        self.assertEqual(r4_params['grant_type'], 'password')
        self.assertEqual(r4_params['username'], self.username)
        self.assertEqual(r4_params['password'], self.password)
        self.assertEqual(r4_params['client_id'], self.client_id)
        self.assertEqual(r4_params['client_secret'], '')

        # scenario 4b`,` client_secret is `None`
        r4b = client.prepare_request_body(username=self.username,
                                          password=self.password,
                                          include_client_id=True,
                                          client_secret=None)
        r4b_params = dict(urlparse.parse_qsl(r4b, keep_blank_values=True))
        self.assertEqual(len(r4b_params.keys()), 4)
        self.assertEqual(r4b_params['grant_type'], 'password')
        self.assertEqual(r4b_params['username'], self.username)
        self.assertEqual(r4b_params['password'], self.password)
        self.assertEqual(r4b_params['client_id'], self.client_id)
Пример #6
0
client_id = '*****@*****.**'
client_secret = 'password'
username = '******'
password = '******'

app.logger.debug(" *** Variables setup ***")

# print Config.DEBUG
# print OAuthConfig.RAS_FRONTSTAGE_CLIENT_ID

# Create an OAuth session. This will handle the send and response http message, and formatting for us.

client = LegacyApplicationClient(client_id=client_id)
client.prepare_request_body(username=username,
                            password=password,
                            scope=['ci.write', 'ci.read'])
oauth = OAuth2Session(client=client)

app.logger.debug(
    " OAuth2 Session has been created for client: {}".format(client_id))

token = oauth.fetch_token(token_url='http://localhost:8000/api/v1/tokens/',
                          username=username,
                          password=password,
                          client_id=client_id,
                          client_secret=client_secret)

app.logger.debug(" *** Access Token Granted *** ")
app.logger.debug(" Values are: ")
for key in token:
Пример #7
0
class StoreOnceOauth2Session(Requester):

    # TODO: In case of an update, the tmpfs will be deleted. This is no problem at first sight as a
    # new "fetch_token" will be triggered, however we should find better place for such tokens.
    _token_dir = Path(cmk.utils.paths.tmp_dir,
                      "special_agents/agent_storeonce4x")
    _token_file_suffix = "%s_oAuthToken.json"
    _refresh_endpoint = "/pml/login/refresh"
    _token_endpoint = "/pml/login/authenticate"
    _dt_fmt = "%Y-%m-%d %H:%M:%S.%f"

    def __init__(self, host: str, port: str, user: str, secret: str,
                 verify_ssl: bool) -> None:
        self._host = host
        self._token_file = "%s/%s" % (str(
            self._token_dir), self._token_file_suffix % self._host)
        self._port = port
        self._user = user
        self._secret = secret
        self._verify_ssl = verify_ssl
        if not verify_ssl:
            urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

        # We need to use LegacyClient due to grant_type==password
        self._client = LegacyApplicationClient(None)
        self._client.prepare_request_body(username=self._user,
                                          password=self._secret)

        # Check if token file exists, read it & create OAuthSession with it
        try:
            self._json_token = self.load_token_file_and_update_expire_in()
            LOGGER.debug("Loaded token content: %s", self._json_token)

            self._oauth_session = OAuth2Session(
                self._user,
                client=self._client,
                auto_refresh_url="https://%s:%s%s" %
                (self._host, self._port, self._refresh_endpoint),
                token_updater=lambda x: self.
                store_token_file_and_update_expires_in_abs(to_token_dict(x)),
                token={
                    "access_token": self._json_token["access_token"],
                    "refresh_token": self._json_token["refresh_token"],
                    "expires_in": self._json_token["expires_in"],
                },
            )
        except (FileNotFoundError, KeyError):
            LOGGER.debug(
                "Token file not found or error in token file. Creating new connection."
            )
            self._oauth_session = OAuth2Session(
                self._user,
                client=self._client,
                auto_refresh_url="https://%s:%s%s" %
                (self._host, self._port, self._refresh_endpoint),
                token_updater=lambda x: self.
                store_token_file_and_update_expires_in_abs(to_token_dict(x)),
            )
            # Fetch token
            token_dict = to_token_dict(
                self._oauth_session.fetch_token(
                    token_url="https://%s:%s%s" %
                    (self._host, self._port, self._token_endpoint),
                    username=self._user,
                    password=self._secret,
                    verify=self._verify_ssl,
                ))
            # Initially create the token file
            self.store_token_file_and_update_expires_in_abs(token_dict)
            self._json_token = token_dict

    def store_token_file_and_update_expires_in_abs(
            self, token_dict: TokenDict) -> None:
        if not self._token_dir.exists():
            self._token_dir.mkdir(parents=True)

        # Update expires_in_abs:
        # we need this to calculate a current "expires_in" (in seconds)
        token_dict["expires_in_abs"] = self.get_absolute_expire_time(
            token_dict["expires_in"])

        with open(self._token_file, "w") as token_file:
            json.dump(token_dict, token_file)

    def load_token_file_and_update_expire_in(self) -> TokenDict:
        with open(self._token_file, "r") as token_file:
            token_json = json.load(token_file)

            # Update expires_in from expires_in_abs
            expires_in_abs = token_json["expires_in_abs"]
            expires_in_updated = (dt.datetime.strptime(
                expires_in_abs,
                self._dt_fmt,
            ) - dt.datetime.now())
            token_json["expires_in"] = math.floor(
                expires_in_updated.total_seconds())
            return to_token_dict(token_json)

    def get_absolute_expire_time(self,
                                 expires_in: float,
                                 expires_in_earlier: int = 20) -> str:
        """
        :param: expires_in_earlier: Will calculate an earlier absolute expire time about its
        value in [s].
        """
        # all expires_in are in seconds according to oAuth2 spec
        now = dt.datetime.now()
        dt_expires_in = dt.timedelta(0, expires_in)
        dt_expires_in_earlier = dt.timedelta(0, expires_in_earlier)
        return dt.datetime.strftime(
            now + dt_expires_in - dt_expires_in_earlier, self._dt_fmt)

    def get(self, path: str, parameters: Optional[StringMap] = None) -> Any:
        url = "https://%s:%s%s" % (self._host, self._port, path)
        resp = self._oauth_session.request(
            method="GET",
            headers={"Accept": "application/json"},
            url=url,
            verify=self._verify_ssl,
        )
        if resp.status_code != 200:
            LOGGER.warning("Call to %s returned HTTP %s.", url,
                           resp.status_code)
        return resp.json()