Base64 Authentication Python
Question:
I’m following an api and I need to use a Base64 authentication of my User Id and password.
‘User ID and Password need to both be concatenated and then Base64 encoded’
it then shows the example
'userid:password'
It then proceeds to say ‘Provide the encoded value in an “Authorization Header”‘
‘for example: Authorization: BASIC {Base64-encoded value}‘
How do I write this into a python api request?
z = requests.post(url, data=zdata )
Thanks
Answers:
You can encode the data and make the request by doing the following:
import requests, base64
usrPass = "userid:password"
b64Val = base64.b64encode(usrPass)
r=requests.post(api_URL,
headers={"Authorization": "Basic %s" % b64Val},
data=payload)
I’m not sure if you’ve to add the “BASIC” word in the Authorization field or not. If you provide the API link, It’d be more clear.
The requests library has Basic Auth support and will encode it for you automatically. You can test it out by running the following in a python repl
from requests.auth import HTTPBasicAuth
r = requests.post(api_URL, auth=HTTPBasicAuth('user', 'pass'), data=payload)
You can confirm this encoding by typing the following.
r.request.headers['Authorization']
outputs:
u'Basic c2RhZG1pbmlzdHJhdG9yOiFTRG0wMDY4'
With python3, I have found a solution which is working for me:
import base64
userpass = username + ':' + password
encoded_u = base64.b64encode(userpass.encode()).decode()
headers = {"Authorization" : "Basic %s" % encoded_u}
To explain let’s use interpreter:
>>> import base64
>>> userpass = "usrname:pass"
>>> print(base64.b64encode(userpass.encode()).decode())
dXNybmFtZTpwYXNzn #That is fine b64 string
>>> print(base64.b64encode(userpass.encode()))
b'dXNybmFtZTpwYXNz' #this is byte code
>>> print(base64.b64encode(userpass))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/Cellar/[email protected]/3.10.7/Frameworks. /Python.framework/Versions/3.10/lib/python3.10/base64.py", line 58, in b64encode
encoded = binascii.b2a_base64(s, newline=False)
TypeError: a bytes-like object is required, not 'str'
You can see that base64.b64encode requires byte type and return bytetype so we have to use builtin decode() and encode() https://www.programiz.com/python-programming/methods/string/encode func to give the bytecode and to get the string again
As explained in the Requests documentation https://2.python-requests.org/en/latest/user/authentication/
Making requests with HTTP Basic Auth is very simple:
>>> from requests.auth import HTTPBasicAuth
>>> requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass'))
<Response [200]>
In fact, HTTP Basic Auth is so common that Requests provides a handy shorthand for using it:
>>> requests.get('https://api.github.com/user', auth=('user', 'pass'))
<Response [200]>
Providing the credentials in a tuple like this is exactly the same as
the HTTPBasicAuth example above.
I found "basicauth" package, it really made my that day. Using pip we can install.
pip install basicauth
Example client side code:
from flask import request
import basicauth
username = request.form['username']
passwd = request.form['password']
encoded_creds = basicauth.encode(username, passwd)
headers = {
"Authorization": "{0}".format(encoded_creds) # Replaces as "Authorization": "Basic WdfV0Adh4Kdf="
}
r = requests.post("http://10.0.0.1:8008/login"), headers=headers)
res = r.json()
print(res)
Example server side code
import basicauth
from flask import request
authorization = request.headers.get('Authorization')
if authorization is not None and "Basic " in authorization:
username, passwd = basicauth.decode(authorization)
print(username, passwd)
I recommend to use:
import request
auth = ('username', 'password')
r = requests.post(url, auth=auth)
Or
import request
from requests.auth import HTTPBasicAuth
auth = HTTPBasicAuth('username', 'password')
r = requests.post(url, auth=auth)
https://2.python-requests.org/en/master/user/authentication/#basic-authentication
In python3, the data needs to be encoded:
import requests, base64
headers = {"Authorization": f"Basic {base64.b64encode(b'userid:password').decode()}"}
requests.post(url, headers=headers, data={})
For python3 you need to convert user-password combination into bytes.
>>> import base64
>>> id_secret_bytes = bytes('client_id' + ':' + 'client_secret', 'UTF-8')
>>> basic_token = base64.b64encode(id_secret_bytes)
>>> basic_token
b'Y2xpZW50X2lkOmNsaWVudF9zZWNyZXQ='
I’m following an api and I need to use a Base64 authentication of my User Id and password.
‘User ID and Password need to both be concatenated and then Base64 encoded’
it then shows the example
'userid:password'
It then proceeds to say ‘Provide the encoded value in an “Authorization Header”‘
‘for example: Authorization: BASIC {Base64-encoded value}‘
How do I write this into a python api request?
z = requests.post(url, data=zdata )
Thanks
You can encode the data and make the request by doing the following:
import requests, base64
usrPass = "userid:password"
b64Val = base64.b64encode(usrPass)
r=requests.post(api_URL,
headers={"Authorization": "Basic %s" % b64Val},
data=payload)
I’m not sure if you’ve to add the “BASIC” word in the Authorization field or not. If you provide the API link, It’d be more clear.
The requests library has Basic Auth support and will encode it for you automatically. You can test it out by running the following in a python repl
from requests.auth import HTTPBasicAuth
r = requests.post(api_URL, auth=HTTPBasicAuth('user', 'pass'), data=payload)
You can confirm this encoding by typing the following.
r.request.headers['Authorization']
outputs:
u'Basic c2RhZG1pbmlzdHJhdG9yOiFTRG0wMDY4'
With python3, I have found a solution which is working for me:
import base64
userpass = username + ':' + password
encoded_u = base64.b64encode(userpass.encode()).decode()
headers = {"Authorization" : "Basic %s" % encoded_u}
To explain let’s use interpreter:
>>> import base64
>>> userpass = "usrname:pass"
>>> print(base64.b64encode(userpass.encode()).decode())
dXNybmFtZTpwYXNzn #That is fine b64 string
>>> print(base64.b64encode(userpass.encode()))
b'dXNybmFtZTpwYXNz' #this is byte code
>>> print(base64.b64encode(userpass))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/Cellar/[email protected]/3.10.7/Frameworks. /Python.framework/Versions/3.10/lib/python3.10/base64.py", line 58, in b64encode
encoded = binascii.b2a_base64(s, newline=False)
TypeError: a bytes-like object is required, not 'str'
You can see that base64.b64encode requires byte type and return bytetype so we have to use builtin decode() and encode() https://www.programiz.com/python-programming/methods/string/encode func to give the bytecode and to get the string again
As explained in the Requests documentation https://2.python-requests.org/en/latest/user/authentication/
Making requests with HTTP Basic Auth is very simple:
>>> from requests.auth import HTTPBasicAuth >>> requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass')) <Response [200]>
In fact, HTTP Basic Auth is so common that Requests provides a handy shorthand for using it:
>>> requests.get('https://api.github.com/user', auth=('user', 'pass')) <Response [200]>
Providing the credentials in a tuple like this is exactly the same as
the HTTPBasicAuth example above.
I found "basicauth" package, it really made my that day. Using pip we can install.
pip install basicauth
Example client side code:
from flask import request
import basicauth
username = request.form['username']
passwd = request.form['password']
encoded_creds = basicauth.encode(username, passwd)
headers = {
"Authorization": "{0}".format(encoded_creds) # Replaces as "Authorization": "Basic WdfV0Adh4Kdf="
}
r = requests.post("http://10.0.0.1:8008/login"), headers=headers)
res = r.json()
print(res)
Example server side code
import basicauth
from flask import request
authorization = request.headers.get('Authorization')
if authorization is not None and "Basic " in authorization:
username, passwd = basicauth.decode(authorization)
print(username, passwd)
I recommend to use:
import request
auth = ('username', 'password')
r = requests.post(url, auth=auth)
Or
import request
from requests.auth import HTTPBasicAuth
auth = HTTPBasicAuth('username', 'password')
r = requests.post(url, auth=auth)
https://2.python-requests.org/en/master/user/authentication/#basic-authentication
In python3, the data needs to be encoded:
import requests, base64
headers = {"Authorization": f"Basic {base64.b64encode(b'userid:password').decode()}"}
requests.post(url, headers=headers, data={})
For python3 you need to convert user-password combination into bytes.
>>> import base64
>>> id_secret_bytes = bytes('client_id' + ':' + 'client_secret', 'UTF-8')
>>> basic_token = base64.b64encode(id_secret_bytes)
>>> basic_token
b'Y2xpZW50X2lkOmNsaWVudF9zZWNyZXQ='