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

PythonApiPython RequestsAppdynamics

Python Problem Overview


I'm trying to use basic HTTP authentication in python. I am using the Requests library:

auth = requests.post('http://' + hostname, auth=HTTPBasicAuth(user, password))
request = requests.get('http://' + hostname + '/rest/applications')

Response form auth variable:

<<class 'requests.cookies.RequestsCookieJar'>[<Cookie JSESSIONID=cb10906c6219c07f887dff5312fb for appdynamics/controller>]>
200
CaseInsensitiveDict({'content-encoding': 'gzip', 'x-powered-by': 'JSP/2.2', 'transfer-encoding': 'chunked', 'set-cookie': 'JSESSIONID=cb10906c6219c07f887dff5312fb; Path=/controller; HttpOnly', 'expires': 'Wed, 05 Nov 2014 19:03:37 GMT', 'server': 'nginx/1.1.19', 'connection': 'keep-alive', 'pragma': 'no-cache', 'cache-control': 'max-age=78000', 'date': 'Tue, 04 Nov 2014 21:23:37 GMT', 'content-type': 'text/html;charset=ISO-8859-1'})

But when I try to get data from different location, - I'm got 401 error

<<class 'requests.cookies.RequestsCookieJar'>[]>
401
CaseInsensitiveDict({'content-length': '1073', 'x-powered-by': 'Servlet/3.0 JSP/2.2 (GlassFish Server Open Source Edition 3.1.2.2 Java/Oracle Corporation/1.7)', 'expires': 'Thu, 01 Jan 1970 00:00:00 UTC', 'server': 'nginx/1.1.19', 'connection': 'keep-alive', 'pragma': 'No-cache', 'cache-control': 'no-cache', 'date': 'Tue, 04 Nov 2014 21:23:37 GMT', 'content-type': 'text/html', 'www-authenticate': 'Basic realm="controller_realm"'})

As far as I understand - in second request are not substituted session parameters.

Python Solutions


Solution 1 - Python

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 - Python

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 - Python

In Python3 it becomes easy:

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

Solution 4 - Python

Below one worked for me

#!/usr/bin/python3
import xml.etree.ElementTree as ET
import requests
from requests.auth import HTTPBasicAuth

url = 'http://172.25.38.135:600/service/xx/users'      # my URL     
response = requests.get(url, auth=HTTPBasicAuth('admin', 'adminpass!'))

string_xml = response.content
tree = ET.fromstring(string_xml)
ET.dump(tree)

Solution 5 - Python

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()

Solution 6 - Python

The following worked for me

from requests.auth import HTTPDigestAuth
url = 'https://someserver.com'
requests.get(url, auth=HTTPDigestAuth('user', 'pass'))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionoleksiiView Question on Stackoverflow
Solution 1 - PythonMartijn PietersView Answer on Stackoverflow
Solution 2 - PythonKuppuramView Answer on Stackoverflow
Solution 3 - Pythonalireza ranjbaranView Answer on Stackoverflow
Solution 4 - PythonAntoView Answer on Stackoverflow
Solution 5 - PythonDarkIDEView Answer on Stackoverflow
Solution 6 - PythoncodeaprendizView Answer on Stackoverflow