Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a python http-client which automatically performs authentication for several auth types?

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?

like image 608
Uli Klank Avatar asked Jun 08 '26 03:06

Uli Klank


1 Answers

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.

like image 152
Nicolas Avatar answered Jun 10 '26 19:06

Nicolas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!