API misinterpreting a password with special characters

Viewed 651

I use a python code to connect to an API to retrieve information in json format. A password is used for the authentication to the API. The authentication was working fine so far, but since I changed my password into one with special characters, things went wrong. i guess the password is not well handled either by the API or the code I use.

This is the piece of code that seems to cause the errors:

        # Create connection and request header.
        # This class does not perform any verification of the server`s certificate.
        conn = HTTPSConnection(ADDRESS)
        auth_header = 'Basic %s' % (':'.join([USER_NAME, PASSWORD]).encode('Base64').strip('\r\n'))
        request_header = {'Authorization':auth_header.decode(),
                        'Content-Type': content_type}

The error I get after executing the code is the following:

    response = self.perform_request(log, 'GET', 'network', params=query)
  File "/usr/local/lib/python2.7/query_code.py", line 103, in perform_request
    auth_header = 'Basic %s' % str(":".join([USER_NAME, PASSWORD]).encode('Base64').strip('\r\n'))
TypeError: sequence item 1: expected string or Unicode, NoneType found

I should have had a successful connection to the API with code 200 and results returned in json format.

I have difficulties spotting the origin of all this, and would like to have your opinion on what I think it is, and how to solve it.

1 Answers

Try this instead:

def basic_token(key, secret):
    return base64.b64encode(bytes(f'{key}:{secret}', 'utf-8')).decode('utf-8')

auth_header = f'basic {basic_token(USERNAME, PASSWORD)}'

If you are using a python version < 3.6, you will need to use .format instead of f-strings:

def basic_token(key, secret):
    return base64.b64encode(bytes('{}:{}'.format(key, secret), 'utf-8')).decode('utf-8')

auth_header = 'basic {}'.format(basic_token(USERNAME, PASSWORD))
Related