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
Provenance
- Commit
7fdb09b- Tree
a6a0924- Author
Idan Gazit <idan@gazit.me>- Committer
Idan Gazit <idan@gazit.me>- Parent
76dacaf
5 files changed+53 added−75 removed
modified:docs/user/advanced.rst+17 added-16 removed
209 unmodified lines210 ---------------------211 212 Requests allows you to use specify your own authentication mechanism.213 214-When you pass our authentication tuple to a request method, the first215-string is the type of authentication. 'basic' is inferred if none is216-provided.214+Any callable which is passed as the ``auth`` argument to a request method will215+have the opportunity to modify the request before it is dispatched.216 218-You can pass in a callable object instead of a string for the first item219-in the tuple, and it will be used in place of the built in authentication220-callbacks.217+Authentication implementations are subclasses of ``requests.auth.AuthBase``,218+and are easy to define. Requests provides two common authentication scheme219+implementations in ``requests.auth``: ``HTTPBasicAuth`` and ``HTTPDigestAuth``.220 221 Let'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.223 225-We simply need to define a callback function that will be used to update the226-Request object, right before it is dispatched.227-224 ::225 230- 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 r237 235- return r236-238 Then, we can make a request using our Pizza Auth::239 239- >>> requests.get('http://pizzabin.org/admin', auth=(pizza_auth, 'kenneth'))240+ >>> requests.get('http://pizzabin.org/admin', auth=PizzaAuth('kenneth'))241 <Response [200]>242 243 244 Verbose Logging11 unmodified linesmodified:docs/user/quickstart.rst+4 added-2 removed
233 unmodified lines234 authentication, but the most common is HTTP Basic Auth.235 236 Making requests with Basic Auth is extremely simple::237 238+ >>> 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]>241 242 OAuth Authentication243 --------------------5 unmodified lines249 ---------------------250 251 Another popular form of web service protection is Digest Authentication::252 253+ >>> 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]>257 258 259 Redirection and History69 unmodified linesmodified:requests/auth.py+25 added-47 removed
14 unmodified lines15 16 from .utils import randombytes, parse_dict_header17 18 19-def http_basic(r, username, password):20- """Attaches HTTP Basic Authentication to the given Request object.21- Arguments should be considered non-positional.19+class AuthBase(object):20+ """Base class that all auth implementations derive from"""21 23- """24- username = str(username)25- password = str(password)22+ def __call__(self, r):23+ raise NotImplementedError('Auth hooks must be callable.')24 27- auth_s = b64encode('%s:%s' % (username, password))28- r.headers['Authorization'] = ('Basic %s' % auth_s)25 30- return r26+class 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)31 32+ def __call__(self, r):33+ auth_s = b64encode('%s:%s' % (self.username, self.password))34+ r.headers['Authorization'] = ('Basic %s' % auth_s)35+ return r36 33-def http_digest(r, username, password):34- """Attaches HTTP Digest Authentication to the given Request object.35- Arguments should be considered non-positional.36- """37 38+class HTTPDigestAuth(AuthBase):39+ """Attaches HTTP Digest Authentication to the given Request object."""40+ def __init__(self, username, password):41+ self.username = username42+ self.password = password43+38- def handle_401(r):44+ def handle_401(self, r):45 """Takes the given response and tries digest-auth, if needed."""46 47 s_auth = r.headers.get('www-authenticate', '')48 26 unmodified lines75 entdig = None76 p_parsed = urlparse(r.request.url)77 path = p_parsed.path + p_parsed.query78 73- 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)81 82 if qop == 'auth':83 if nonce == last_nonce:16 unmodified lines100 return None101 102 # 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)112 107-113 r.request.headers['Authorization'] = 'Digest %s' % (base)114 r.request.send(anyway=True)115 _r = r.request.response116 _r.history.append(r)1 unmodified line118 return _r119 120 return r121 117- r.hooks['response'] = handle_401118- return r119-120-121-def dispatch(t):122- """Given an auth tuple, return an expanded version."""123-124- if not t:125- return t126- else:127- t = list(t)128-129- # Make sure they're passing in something.130- assert len(t) >= 2131-132- # If only two items are passed in, assume HTTPBasic.133- if (len(t) == 2):134- t.insert(0, 'basic')135-136- # 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_digest142-143- # Return a custom callable.144- return (t[0], tuple(t[1:]))145-146-122+ def __call__(self, r):123+ r.hooks['response'] = self.handle_401124+ return rmodified:requests/models.py+3 added-7 removed
12 unmodified lines13 from Cookie import SimpleCookie14 from urlparse import urlparse, urlunparse, urljoin, urlsplit15 from datetime import datetime16 17-from .auth import dispatch as auth_dispatch17 from .hooks import dispatch_hook18 from .structures import CaseInsensitiveDict19 from .status_codes import codes20 from .packages.urllib3.exceptions import MaxRetryError76 unmodified lines97 #: content and metadata of HTTP Response, once :attr:`sent <send>`.98 self.response = Response()99 100 #: Authentication tuple to attach to :class:`Request <Request>`.102- self._auth = auth103- self.auth = auth_dispatch(auth)101+ self.auth = auth102 103 #: CookieJar to attach to :class:`Request <Request>`.104 self.cookies = dict(cookies or [])105 126 unmodified lines232 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 lines389 self.headers['Content-Type'] = content_type390 391 392 if self.auth:395- auth_func, auth_args = self.auth396-393 # Allow auth to make its changes.398- r = auth_func(self, *auth_args)394+ r = self.auth(self)395 396 # Update self to reflect the auth changes.397 self.__dict__.update(r.__dict__)398 216 unmodified linesmodified:test_requests.py+4 added-3 removed
8 unmodified lines9 10 import requests11 import envoy12 from requests import HTTPError13+from requests.auth import HTTPBasicAuth, HTTPDigestAuth14 15 try:16 import omnijson as json17 except ImportError:126 unmodified lines144 def test_BASICAUTH_HTTP_200_OK_GET(self):145 146 for service in SERVICES:147 147- auth = ('user', 'pass')148+ auth = HTTPBasicAuth('user', 'pass')149 url = service('basic-auth', 'user', 'pass')150 151 r = requests.get(url, auth=auth)152 self.assertEqual(r.status_code, 200)10 unmodified lines163 def test_DIGESTAUTH_HTTP_200_OK_GET(self):164 165 for service in SERVICES:166 166- auth = ('digest', 'user', 'pass')167+ auth = HTTPDigestAuth('user', 'pass')168 url = service('digest-auth', 'auth', 'user', 'pass')169 170 r = requests.get(url, auth=auth)171 self.assertEqual(r.status_code, 200)98 unmodified lines270 271 272 def test_httpauth_recursion(self):273 273- http_auth = ('user', 'BADpass')274+ http_auth = HTTPBasicAuth('user', 'BADpass')275 276 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