Base64 Authentication Python

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'

Need Your Help

how to share a variable across modules for all tests in py.test

python unit-testing testing global-variables pytest

I have multiple tests run by py.test that are located in multiple classes in multiple files.

Separators in Xamarin.Forms

xamarin xamarin.forms

I'd like to use horizontal separator lines in a form. As far as I found out, Xamarin.Forms doesn't provide one.