Merge branch 'auth_callables' of https://github.com/idangazit/requests into develop
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Conflicts: requests/models.py
authored by Kenneth Reitz · committed by Kenneth Reitz · parents 65c0657, 1933d3c · Browse files · 5 files·+91 added−79 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+91 added−79 removed
- other:+91 added−79 removed
Provenance
- Commit
a7a619b- Tree
567bb7f- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
65c0657- Parent 2
1933d3c
5 files changed+91 added−79 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+18 added-5 removed
263 unmodified lines264 authentication, but the most common is HTTP Basic Auth.265 266 Making requests with Basic Auth is extremely simple::267 268+ >>> from requests.auth import HTTPBasicAuth269+ >>> requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass'))270+ <Response [200]>271+272+Due to the prevalence of HTTP Basic Auth, requests provides a shorthand for273+this authentication method::274+275 >>> requests.get('https://api.github.com/user', auth=('user', 'pass'))276 <Response [200]>277 271-OAuth Authentication272---------------------278+Providing the credentials as a tuple in this fashion is functionally equivalent279+to the ``HTTPBasicAuth`` example above.280 274-Miguel Araujo's `requests-oauth <http://pypi.python.org/pypi/requests-oauth>`_ project provides a simple interface for275-establishing OAuth connections. Documentation and examples can be found on the requests-oauth `git repository <https://github.com/maraujop/requests-oauth>`_.281 282 Digest Authentication283 ---------------------284 285 Another popular form of web service protection is Digest Authentication::286 287+ >>> from requests.auth import HTTPDigestAuth288 >>> url = 'http://httpbin.org/digest-auth/auth/user/pass'283- >>> requests.get(url, auth=('digest', 'user', 'pass'))289+ >>> requests.get(url, auth=HTTPDigestAuth('user', 'pass'))290 <Response [200]>291 292 293+OAuth Authentication294+--------------------295+296+Miguel Araujo's `requests-oauth <http://pypi.python.org/pypi/requests-oauth>`_ project provides a simple interface for297+establishing OAuth connections. Documentation and examples can be found on the requests-oauth `git repository <https://github.com/maraujop/requests-oauth>`_.298+299+300 Redirection and History301 -----------------------302 303 Requests will automatically perform location redirection while using impodotent methods.66 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+8 added-8 removed
11 unmodified lines12 13 from urlparse import urlparse, urlunparse, urljoin, urlsplit14 from datetime import datetime15 16-from .auth import dispatch as auth_dispatch16 from .hooks import dispatch_hook17 from .structures import CaseInsensitiveDict18 from .status_codes import codes19 from .packages import oreos20+from .auth import HTTPBasicAuth21 from .packages.urllib3.exceptions import MaxRetryError22 from .packages.urllib3.exceptions import SSLError as _SSLError23 from .packages.urllib3.exceptions import HTTPError as _HTTPError24 from .packages.urllib3 import connectionpool, poolmanager72 unmodified lines97 #: :class:`Response <Response>` instance, containing98 #: content and metadata of HTTP Response, once :attr:`sent <send>`.99 self.response = Response()100 101- #: Authentication tuple to attach to :class:`Request <Request>`.102- self._auth = auth103- self.auth = auth_dispatch(auth)101+ #: Authentication tuple or object to attach to :class:`Request <Request>`.102+ self.auth = auth103 104 #: CookieJar to attach to :class:`Request <Request>`.105 self.cookies = dict(cookies or [])106 122 unmodified lines229 headers=headers,230 files=self.files,231 method=method,232 params=self.session.params,234- auth=self._auth,233+ auth=self.auth,234 cookies=cookies,235 redirect=True,236 config=self.config,237 timeout=self.timeout,152 unmodified lines390 # Add content-type if it wasn't explicitly provided.391 if (content_type) and (not 'content-type' in self.headers):392 self.headers['Content-Type'] = content_type393 395-394 if self.auth:397- auth_func, auth_args = self.auth395+ if isinstance(self.auth, tuple) and len(self.auth) == 2:396+ # special-case basic HTTP auth397+ self.auth = HTTPBasicAuth(*self.auth)398 399 # Allow auth to make its changes.400- r = auth_func(self, *auth_args)400+ r = self.auth(self)401 402 # Update self to reflect the auth changes.403 self.__dict__.update(r.__dict__)404 231 unmodified linesmodified:test_requests.py+23 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:122 unmodified lines140 r = requests.patch(httpbin('patch'))141 self.assertEqual(r.status_code, 200)142 143 143- def test_BASICAUTH_HTTP_200_OK_GET(self):144+ def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self):145 146 for service in SERVICES:147 148 auth = ('user', 'pass')10 unmodified lines159 r = s.get(url)160 self.assertEqual(r.status_code, 200)161 162 163+ def test_BASICAUTH_HTTP_200_OK_GET(self):164+165+ for service in SERVICES:166+167+ auth = HTTPBasicAuth('user', 'pass')168+ url = service('basic-auth', 'user', 'pass')169+170+ r = requests.get(url, auth=auth)171+ self.assertEqual(r.status_code, 200)172+173+ r = requests.get(url)174+ self.assertEqual(r.status_code, 401)175+176+177+ s = requests.session(auth=auth)178+ r = s.get(url)179+ self.assertEqual(r.status_code, 200)180+181+182 def test_DIGESTAUTH_HTTP_200_OK_GET(self):183 184 for service in SERVICES:185 166- auth = ('digest', 'user', 'pass')186+ auth = HTTPDigestAuth('user', 'pass')187 url = service('digest-auth', 'auth', 'user', 'pass')188 189 r = requests.get(url, auth=auth)190 self.assertEqual(r.status_code, 200)98 unmodified lines289 290 291 def test_httpauth_recursion(self):292 273- http_auth = ('user', 'BADpass')293+ http_auth = HTTPBasicAuth('user', 'BADpass')294 295 for service in SERVICES:296 r = requests.get(service('basic-auth', 'user', 'pass'), auth=http_auth)297 self.assertEquals(r.status_code, 401)281 unmodified lines