I am currently using urllib2 or curl to perform authentication to different Trac, Jira, Twiki and Media Wiki sites to request information like the users that are active.
Now depending on the settings on the specific instance I currently need to specify how to perform the authentication (e.g. trac uses either Basic or Digest auth scheme).
Is there a (python) library or a piece of code that automatically identifies the server's auth scheme and performs given url, username, and password to eliminate this server-specific setting as a constant source of error?
Python Requests don't handle authentication scheme automatically but provides a simpler interface to handle both Basic and Digest.
Check http://www.python-requests.org/en/latest/user/authentication/ for code examples.
The code below try to get the url once to get the authentication scheme, then retry the url with the correct Auth implementation:
import requests
import sys
from requests.auth import HTTPBasicAuth, HTTPDigestAuth
AUTH_MAP = {
'basic': HTTPBasicAuth,
'digest': HTTPDigestAuth,
}
def auth_get(url, *args, **kwargs):
r = requests.get(url)
if r.status_code != 401:
return r
auth_scheme = r.headers['WWW-Authenticate'].split(' ')[0]
auth = AUTH_MAP.get(auth_scheme.lower())
if not auth:
raise ValueError('Unknown authentication scheme')
r = requests.get(url, auth=auth(*args, **kwargs))
return r
if __name__ == '__main__':
print auth_get(*sys.argv[1:])
Test it with python test_request.py username password.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With