Reputation: 647
I'm trying to connect to an API and I've to encode64 the username and password. The 'Authorisation' value should look like this: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ
When I try to connect I get an error: 'Unauthorized: Bad credentials'. The support says that my credentials are ok, but they are slow to respond to solve my issue.
I suspect the encoding part of the code, but I'm not sure. Could you please take a look at my code and tell me what could be wrong with it?
The direct link to the section about authentication in the documentation : http://developer.outbrain.com/home-page/amplify-api/documentation/#/reference/authentications/via-api
m = str(base64.b64encode(b'xxxxx:xxxxxxx'))
headers = {
'Authorization': 'Basic ' + m + ''
}
r = requests.get('https://api.outbrain.com/amplify/v0.1/login', headers=headers)
print(r.json())
Upvotes: 5
Views: 9045
Reputation: 323
Another way to do it:
import base64
message = "user:password"
message_bytes = message.encode('ascii')
base64_bytes = base64.b64encode(message_bytes)
base64_message = base64_bytes.decode('ascii')
print(base64_message)
Upvotes: 1
Reputation: 11157
You need to use decode
to correctly get a string from the byte sequence:
Wrong (note the 'b' prefix and single quotes in the result):
>>> str(base64.b64encode(b'test'))
"b'dGVzdA=='"
Right:
>>> base64.b64encode(b'test').decode('utf-8')
'dGVzdA=='
Additionally, requests
can do this for you:
from requests.auth import HTTPBasicAuth
r = requests.get('https://api.outbrain.com/amplify/v0.1/login', auth=HTTPBasicAuth('user', 'pass'))
Upvotes: 10