Skip to content
Myr

Converted auth to use callable objects instead of tuples.

Before adoption: this commit came in with the history the project adopted, so no landing records it.

My attempt to address #275 on kennethreitz/requests.

authored by Idan Gazit · committed by Idan Gazit · parent 76dacaf · Browse files · 5 files+53 added−75 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+53 added−75 removed

  • other:+53 added−75 removed

5 files+53 added−75 removed

modified:docs/user/advanced.rst+17 added-16 removed
209 unmodified lines
210---------------------211212Requests allows you to use specify your own authentication mechanism.213214When you pass our authentication tuple to a request method, the first215string is the type of authentication. 'basic' is inferred if none is216provided.214Any callable which is passed as the ``auth`` argument to a request method will215have the opportunity to modify the request before it is dispatched.216218You can pass in a callable object instead of a string for the first item219in the tuple, and it will be used in place of the built in authentication220callbacks.217Authentication implementations are subclasses of ``requests.auth.AuthBase``,218and are easy to define. Requests provides two common authentication scheme219implementations in ``requests.auth``: ``HTTPBasicAuth`` and ``HTTPDigestAuth``.220221Let's pretend that we have a web service that will only respond if the222``X-Pizza`` header is set to a password value. Unlikely, but just go with it.223225We simply need to define a callback function that will be used to update the226Request object, right before it is dispatched.227224::225230 def pizza_auth(r, username):231 """Attaches HTTP Pizza Authentication to the given Request object.232 """233 r.headers['X-Pizza'] = username226 from requests.auth import AuthBase227 class PizzaAuth(AuthBase):228 """Attaches HTTP Pizza Authentication to the given Request object."""229 def __init__(self, username):230 # setup any auth-related data here231 self.username = username232 233 def __call__(self, r):234 # modify and return the request235 r.headers['X-Pizza'] = self.username236 return r237235 return r236238Then, we can make a request using our Pizza Auth::239239 >>> requests.get('http://pizzabin.org/admin', auth=(pizza_auth, 'kenneth'))240 >>> requests.get('http://pizzabin.org/admin', auth=PizzaAuth('kenneth'))241 <Response [200]>242243244Verbose Logging
11 unmodified lines
modified:docs/user/quickstart.rst+4 added-2 removed
233 unmodified lines
234authentication, but the most common is HTTP Basic Auth.235236Making requests with Basic Auth is extremely simple::237238 >>> from requests.auth import HTTPBasicAuth238 >>> requests.get('https://api.github.com/user', auth=('user', 'pass'))239 >>> requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass'))240 <Response [200]>241242OAuth Authentication243--------------------
5 unmodified lines
249---------------------250251Another popular form of web service protection is Digest Authentication::252253 >>> from requests.auth import HTTPDigestAuth254 >>> url = 'http://httpbin.org/digest-auth/auth/user/pass'253 >>> requests.get(url, auth=('digest', 'user', 'pass'))255 >>> requests.get(url, auth=HTTPDigestAuth('user', 'pass'))256 <Response [200]>257258259Redirection and History
69 unmodified lines
modified:requests/auth.py+25 added-47 removed
14 unmodified lines
1516from .utils import randombytes, parse_dict_header171819def http_basic(r, username, password):20 """Attaches HTTP Basic Authentication to the given Request object.21 Arguments should be considered non-positional.19class AuthBase(object):20 """Base class that all auth implementations derive from"""2123 """24 username = str(username)25 password = str(password)22 def __call__(self, r):23 raise NotImplementedError('Auth hooks must be callable.')2427 auth_s = b64encode('%s:%s' % (username, password))28 r.headers['Authorization'] = ('Basic %s' % auth_s)2530 return r26class HTTPBasicAuth(AuthBase):27 """Attaches HTTP Basic Authentication to the given Request object."""28 def __init__(self, username, password):29 self.username = str(username)30 self.password = str(password)3132 def __call__(self, r):33 auth_s = b64encode('%s:%s' % (self.username, self.password))34 r.headers['Authorization'] = ('Basic %s' % auth_s)35 return r3633def http_digest(r, username, password):34 """Attaches HTTP Digest Authentication to the given Request object.35 Arguments should be considered non-positional.36 """3738class HTTPDigestAuth(AuthBase):39 """Attaches HTTP Digest Authentication to the given Request object."""40 def __init__(self, username, password):41 self.username = username42 self.password = password4338 def handle_401(r):44 def handle_401(self, r):45 """Takes the given response and tries digest-auth, if needed."""4647 s_auth = r.headers.get('www-authenticate', '')48
26 unmodified lines
75 entdig = None76 p_parsed = urlparse(r.request.url)77 path = p_parsed.path + p_parsed.query7873 A1 = "%s:%s:%s" % (username, realm, password)79 A1 = "%s:%s:%s" % (self.username, realm, self.password)80 A2 = "%s:%s" % (r.request.method, path)8182 if qop == 'auth':83 if nonce == last_nonce:
16 unmodified lines
100 return None101102 # XXX should the partial digests be encoded too?103 base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \98 'response="%s"' % (username, realm, nonce, path, respdig)104 'response="%s"' % (self.username, realm, nonce, path, respdig)105 if opaque:106 base += ', opaque="%s"' % opaque107 if entdig:108 base += ', digest="%s"' % entdig109 base += ', algorithm="%s"' % algorithm110 if qop:111 base += ', qop=auth, nc=%s, cnonce="%s"' % (ncvalue, cnonce)112107113 r.request.headers['Authorization'] = 'Digest %s' % (base)114 r.request.send(anyway=True)115 _r = r.request.response116 _r.history.append(r)
1 unmodified line
118 return _r119120 return r121117 r.hooks['response'] = handle_401118 return r119120121def dispatch(t):122 """Given an auth tuple, return an expanded version."""123124 if not t:125 return t126 else:127 t = list(t)128129 # Make sure they're passing in something.130 assert len(t) >= 2131132 # If only two items are passed in, assume HTTPBasic.133 if (len(t) == 2):134 t.insert(0, 'basic')135136 # Allow built-in string referenced auths.137 if isinstance(t[0], basestring):138 if t[0] in ('basic', 'forced_basic'):139 t[0] = http_basic140 elif t[0] in ('digest',):141 t[0] = http_digest142143 # Return a custom callable.144 return (t[0], tuple(t[1:]))145146122 def __call__(self, r):123 r.hooks['response'] = self.handle_401124 return r
modified:requests/models.py+3 added-7 removed
12 unmodified lines
13from Cookie import SimpleCookie14from urlparse import urlparse, urlunparse, urljoin, urlsplit15from datetime import datetime1617from .auth import dispatch as auth_dispatch17from .hooks import dispatch_hook18from .structures import CaseInsensitiveDict19from .status_codes import codes20from .packages.urllib3.exceptions import MaxRetryError
76 unmodified lines
97 #: content and metadata of HTTP Response, once :attr:`sent <send>`.98 self.response = Response()99100 #: Authentication tuple to attach to :class:`Request <Request>`.102 self._auth = auth103 self.auth = auth_dispatch(auth)101 self.auth = auth102103 #: CookieJar to attach to :class:`Request <Request>`.104 self.cookies = dict(cookies or [])105
126 unmodified lines
232 headers=headers,233 files=self.files,234 method=method,235 params=self.session.params,238 auth=self._auth,236 auth=self.auth,237 cookies=cookies,238 redirect=True,239 config=self.config,240 timeout=self.timeout,
148 unmodified lines
389 self.headers['Content-Type'] = content_type390391392 if self.auth:395 auth_func, auth_args = self.auth396393 # Allow auth to make its changes.398 r = auth_func(self, *auth_args)394 r = self.auth(self)395396 # Update self to reflect the auth changes.397 self.__dict__.update(r.__dict__)398
216 unmodified lines
modified:test_requests.py+4 added-3 removed
8 unmodified lines
910import requests11import envoy12from requests import HTTPError13from requests.auth import HTTPBasicAuth, HTTPDigestAuth1415try:16 import omnijson as json17except ImportError:
126 unmodified lines
144 def test_BASICAUTH_HTTP_200_OK_GET(self):145146 for service in SERVICES:147147 auth = ('user', 'pass')148 auth = HTTPBasicAuth('user', 'pass')149 url = service('basic-auth', 'user', 'pass')150151 r = requests.get(url, auth=auth)152 self.assertEqual(r.status_code, 200)
10 unmodified lines
163 def test_DIGESTAUTH_HTTP_200_OK_GET(self):164165 for service in SERVICES:166166 auth = ('digest', 'user', 'pass')167 auth = HTTPDigestAuth('user', 'pass')168 url = service('digest-auth', 'auth', 'user', 'pass')169170 r = requests.get(url, auth=auth)171 self.assertEqual(r.status_code, 200)
98 unmodified lines
270271272 def test_httpauth_recursion(self):273273 http_auth = ('user', 'BADpass')274 http_auth = HTTPBasicAuth('user', 'BADpass')275276 for service in SERVICES:277 r = requests.get(service('basic-auth', 'user', 'pass'), auth=http_auth)278 self.assertEquals(r.status_code, 401)
281 unmodified lines