OneSignal / onesignal-python-api

Other
15 stars 6 forks source link

[Bug]: onesignal.Configuration puts wrong values in request headers #19

Open keidikapllani opened 1 year ago

keidikapllani commented 1 year ago

What happened?

If you try to call the API with a configuration as mentioned in the documentation:

configuration = onesignal.Configuration(
    app_key = "YOUR_APP_KEY",
    user_key = "YOUR_USER_KEY"
   api_key= "YOUR_API_KEY"
)

you will get back a 400 Error with the following message:

onesignal.exceptions.ApiException: Status Code: 400
Reason: Bad Request
HTTP response headers: HTTPHeaderDict({'Date': 'Thu, 11 May 2023 15:00:05 GMT', 'Content-Type': 'application/json; charset=utf-8', 'Transfer-Encoding': 'chunked', 'Connection': 'keep-alive', 'x-runtime': '0.007879', 'x-frame-options': 'SAMEORIGIN', 'x-xss-protection': '1; mode=block', 'x-content-type-options': 'nosniff', 'x-download-options': 'noopen', 'x-permitted-cross-domain-policies': 'none', 'referrer-policy': 'strict-origin-when-cross-origin', 'access-control-allow-origin': '*', 'access-control-allow-headers': 'SDK-Version', 'ratelimit-limit': '10', 'ratelimit-remaining': '9', 'ratelimit-reset': '1683817206', 'ratelimit-reference': 'https://documentation.onesignal.com/docs/disabled-apps', 'vary': 'Accept, Origin', 'cache-control': 'no-cache', 'x-request-id': 'e7ad0273-6dea-4380-9809-0f9f9b5c4b83', 'Via': '1.1 google', 'Alt-Svc': 'h3=":443"; ma=86400, h3-29=":443"; ma=86400', 'CF-Cache-Status': 'DYNAMIC', 'Set-Cookie': '__cf_bm=XCgEcA70LiVj5FTAN5u_HqoA760wcxsJ8dgpCuY7wTY-1683817205-0-ATaNIhn68N2lI3jcFoIbR+YUPQfEoIL9bhMNY2rOcuG3wU/+FQkoeg1JeWtN5SLsQS/yJZRJXieGL962WI8qT4Y=; path=/; expires=Thu, 11-May-23 15:30:05 GMT; domain=.onesignal.com; HttpOnly; Secure; SameSite=None', 'Strict-Transport-Security': 'max-age=15552000; includeSubDomains', 'Server': 'cloudflare', 'CF-RAY': '7c5b4a1f6ff7417d-LHR'})
HTTP response body: {"errors":["Please include a case-sensitive header of Authorization: Basic \u003cYOUR-REST-API-KEY-HERE\u003e or Bearer token=\"\u003cYOUR-REST-API-KEY-HERE\u003e\" with a valid REST API key."],"reference":["https://documentation.onesignal.com/docs/accounts-and-keys#section-keys-ids"]}

Code snippet to reproduce:

 import onesignal
 config = onesignal.Configuration(
        app_key="APP_KEY",
        api_key="API_KEY",
    )
 with ApiClient(config) as api_client:
        # Create an instance of the API class
        api_instance = default_api.DefaultApi(api_client)
        app_id = "APP_ID"# The app ID that you want to view notifications from
        limit = 50  # How many notifications to return.  Max is 50.  Default is 50. (optional)
        offset = 0  # Page offset.  Default is 0.  Results are sorted by queued_at in descending order.
        # queued_at is a representation of the time that the notification was queued at. (optional)
        # Kind of notifications returned:   * unset - All notification types (default)
        # * `0` - Dashboard only   * `1` - API only   * `3` - Automated only  (optional)

        # example passing only required values which don't have defaults set
        try:
            # View notifications
            api_response: NotificationSlice = api_instance.get_notifications(app_id)
        except ApiException as e:
            _logger.error("Exception when calling DefaultApi->get_notifications: %s\n" % e)
            raise e

Following the error, it appears to be a bug in onesignal.Configuration, lines 370:382:

    def auth_settings(self):
        """Gets Auth Settings dict for api client.

        :return: The Auth Settings information dict.
        """
        auth = {}
        if self.app_key is not None:
            auth['app_key'] = {
                'type': 'bearer',
                'in': 'header',
                'key': 'Authorization',
                'value': 'Bearer ' + self.app_key
            }

where the last line should be 'Bearer ' + self.api_key

Steps to reproduce?

1. Install the latest sdk
2. Create a configuration using the method described in the docs
3. Try hitting any of the endpoints

What did you expect to happen?

I expected the call to complete successfully and return data.

Relevant log output

File "/.pyenv/versions/common/lib/python3.9/site-packages/onesignal/api/default_api.py", line 4346, in get_notifications
    return self.get_notifications_endpoint.call_with_http_info(**kwargs)
  File "/.pyenv/versions/common/lib/python3.9/site-packages/onesignal/api_client.py", line 881, in call_with_http_info
    return self.api_client.call_api(
  File "/.pyenv/versions/common/lib/python3.9/site-packages/onesignal/api_client.py", line 423, in call_api
    return self.__call_api(resource_path, method,
  File "/.pyenv/versions/common/lib/python3.9/site-packages/onesignal/api_client.py", line 207, in __call_api
    raise e
  File "/.pyenv/versions/common/lib/python3.9/site-packages/onesignal/api_client.py", line 200, in __call_api
    response_data = self.request(
  File ".pyenv/versions/common/lib/python3.9/site-packages/onesignal/api_client.py", line 449, in request
    return self.rest_client.GET(url,
  File "/.pyenv/versions/common/lib/python3.9/site-packages/onesignal/rest.py", line 236, in GET
    return self.request("GET", url,
  File "/.pyenv/versions/common/lib/python3.9/site-packages/onesignal/rest.py", line 230, in request
    raise ApiException(http_resp=r)
onesignal.exceptions.ApiException: Status Code: 400
Reason: Bad Request
HTTP response headers: HTTPHeaderDict({'Date': 'Thu, 11 May 2023 15:12:59 GMT', 'Content-Type': 'application/json; charset=utf-8', 'Transfer-Encoding': 'chunked', 'Connection': 'keep-alive', 'x-runtime': '0.008203', 'x-frame-options': 'SAMEORIGIN', 'x-xss-protection': '1; mode=block', 'x-content-type-options': 'nosniff', 'x-download-options': 'noopen', 'x-permitted-cross-domain-policies': 'none', 'referrer-policy': 'strict-origin-when-cross-origin', 'access-control-allow-origin': '*', 'access-control-allow-headers': 'SDK-Version', 'ratelimit-limit': '10', 'ratelimit-remaining': '9', 'ratelimit-reset': '1683817980', 'ratelimit-reference': 'https://documentation.onesignal.com/docs/disabled-apps', 'vary': 'Accept, Origin', 'cache-control': 'no-cache', 'x-request-id': '2c2989de-f588-4f6e-ba9c-e9e96591f6af', 'Via': '1.1 google', 'Alt-Svc': 'h3=":443"; ma=86400, h3-29=":443"; ma=86400', 'CF-Cache-Status': 'DYNAMIC', 'Set-Cookie': '__cf_bm=ZlxUSzBn3S4gExlljKJ326axtITVJSkPhZBef08rqZE-1683817979-0-AWRT+msUU+kfGQimX/oTh9navAuEC0P3F6BNNHnGVuGi2ijJHQ6+3RBXrSGgXwVZFZluAqKLu3lUv68cEdlj/vc=; path=/; expires=Thu, 11-May-23 15:42:59 GMT; domain=.onesignal.com; HttpOnly; Secure; SameSite=None', 'Strict-Transport-Security': 'max-age=15552000; includeSubDomains', 'Server': 'cloudflare', 'CF-RAY': '7c5b5d021b387447-LHR'})
HTTP response body: {"errors":["Please include a case-sensitive header of Authorization: Basic \u003cYOUR-REST-API-KEY-HERE\u003e or Bearer token=\"\u003cYOUR-REST-API-KEY-HERE\u003e\" with a valid REST API key."],"reference":["https://documentation.onesignal.com/docs/accounts-and-keys#section-keys-ids"]}

Code of Conduct

Afiyetolsun commented 1 year ago

Still not working! Let me check, and i can create PR

Afiyetolsun commented 1 year ago

Here is fix: In onesignal.Configuration, lines 370:392:

 def auth_settings(self):
        """Gets Auth Settings dict for api client.

        :return: The Auth Settings information dict.
        """
        auth = {}
        if self.api_key is not None:
            auth['app_key'] = {
                'type': 'bearer',
                'in': 'header',
                'key': 'Authorization',
                'value': 'Bearer ' + self.api_key
            }

        if self.user_key is not None:
            auth['user_key'] = {
                'type': 'bearer',
                'in': 'header',
                'key': 'Authorization',
                'value': 'Bearer ' + self.user_key
            }

        return auth
hagen00 commented 3 months ago

Does anyone know what the correct setup is? I'm also getting Please include a case-sensitive header of Authorization:...

using

config = onesignal.Configuration(
        app_key="APP_KEY",
        api_key="API_KEY",
    )

What am I supposed to do?