For this example I will use shipstation's api, but this question applies to any api using oAuth tokens.
The ShipStation API uses Basic HTTP authentication. The Authorization header is constructed as follows:
Username (
API_KEY
) and password (API_SECRET
) are combined into a string "username:password"The resulting string is then encoded using the RFC2045-MIME variant of Base64, except not limited to 76 char/line
The authorization method and a space i.e. "Basic " is then put before the encoded string.
For example, if the
API_KEY
given is 'ShipStation' and theAPI_SECRET
is 'Rocks' then the header is formed as follows:Authorization: Basic U2hpcFN0YXRpb246Um9ja3M=
Easy right? My first attempt:
import base64
KEY = 'ShipStation'
SECRET = 'Rocks'
AUTH = bytes(str(KEY) + ':' + str(SECRET), encoding='utf-8')
TOKEN = base64.b64encode(AUTH)
AUTH_TOKEN = 'Basic ' + str(TOKEN)
print(AUTH_TOKEN) # Basic b'U2hpcFN0YXRpb246Um9ja3M='
As you can see, the AUTH_TOKEN
I made has an additional b'
at the beginning and '
at the end, which causes a 401 when you send the request.
Here is my fix to this:
import base64
KEY = 'ShipStation'
SECRET = 'Rocks'
AUTH = bytes(str(KEY) + ':' + str(SECRET), encoding='utf-8')
TOKEN = str(base64.b64encode(AUTH))
AUTH_TOKEN = 'Basic ' + TOKEN[2:len(TOKEN)-1]
print(AUTH_TOKEN) # Basic U2hpcFN0YXRpb246Um9ja3M=
While the above code works, this is clearly not the way it was intended to be done. (I assume?)
TLDR;
What is the pythonic way of turning the TOKEN
in the example above into the proper format?