How do I use basic HTTP authentication with the python Requests library?

Solution 1:

You need to use a session object and send the authentication each request. The session will also track cookies for you:

session = requests.Session()
session.auth = (user, password)

auth = session.post('http://' + hostname)
response = session.get('http://' + hostname + '/rest/applications')

Solution 2:

import requests

from requests.auth import HTTPBasicAuth
res = requests.post('https://api.github.com/user', verify=False, auth=HTTPBasicAuth('user', 'password'))
print(res)

Note: sometimes, we may get SSL error certificate verify failed, to avoid, we can use verify=False

Solution 3:

In Python3 it becomes easy:

import requests
response = requests.get(uri, auth=(user, password))

Solution 4:

for python 2:

base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')

request = urllib2.Request(url)

request.add_header("Authorization", "Basic %s" % base64string) 

result = urllib2.urlopen(request)
        data = result.read()