51

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

2

8 Answers 8

113

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'
3
  • what is payload here ?
    – sdgd
    Oct 21, 2017 at 20:16
  • Payload can be anything ... like data from a form submit, or some json data etc.
    – G.A.
    Mar 23, 2018 at 14:03
  • 3
    I would suggest this answer over the accepted one. It is python-version independent. Jul 24, 2019 at 7:43
61

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.

5
  • e.g. In order to upload an image to Imgur, the Authorization header looks like this: "Client-ID yourClientPublicKey" with the "Client-ID " keyword before the data.
    – Alfageme
    Aug 9, 2013 at 2:21
  • what is payload here ?
    – sdgd
    Oct 21, 2017 at 20:13
  • @Dev whatever the body of the authenticated request you want to send
    – Alfageme
    Oct 22, 2017 at 12:38
  • 20
    in python3 I get TypeError: a bytes-like object is required, not 'str'
    – Felipe
    Jun 16, 2021 at 20:18
  • 1
    @Felipe you need to encode the data .. see my answer. Mar 12, 2022 at 9:07
31

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

5
  • Nice solution, which works for me on python3, too. Thank you. P.S. I added the import base64 statement to your solution.
    – NYCeyes
    May 12, 2020 at 18:32
  • This solution also works for me on python3. Many thanks Aug 3, 2021 at 8:19
  • 1
    This works for me, but I have no clue why we have to encode it, b64encode it, then decode it. Makes no sense, but it works... Oct 27, 2022 at 19:53
  • 2
    @MichaelCox This is because the base64.b64encode() function operates on, and returns /bytes/, not strings. So, first you have to take your string, and encode() it to get the bytes equivalent of the string. Then process it (b64encode() the bytes) which gives you back another bytes result. Then that result must be /decoded/ again to get it back to a normal string.
    – W.Prins
    Nov 30, 2022 at 10:06
  • thank you, it works. but honestly, quite some brain muscles needed for such a simple task like encoding/decoding base64 in python3..
    – Aydin K.
    Feb 9 at 14:46
7

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.

4

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={})
3

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)
1
  • This has really helped me. The basicauth package is particularly good for decoding the Authorization header, which is a harder task than encoding it.
    – Cosmittus
    Nov 13, 2021 at 12:44
2

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

2

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='

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.