auth.py
This file
Path
requests/auth.py
305 lines · 10.0 KiB · Python
Last changed by
Merge pull request #5160 from OrangutanGaming/change-githubNate Prewittbefore adoptiond79024f
History of this fileTake it
The walk stopped after 200 commits: lines older than e4d214d point at it.
Merge pull request #4749 from derlin/masterNate Prewittbefore adoptione4d214d
lines 1–40why, one step back1# -*- coding: utf-8 -*-23"""4requests.auth5~~~~~~~~~~~~~67This module contains the authentication handlers for Requests.8"""910import os11import re12import time13import hashlib14import threading15import warnings1617from base64 import b64encode1819from .compat import urlparse, str, basestring20from .cookies import extract_cookies_to_jar21from ._internal_utils import to_native_string22from .utils import parse_dict_header2324CONTENT_TYPE_FORM_URLENCODED = 'application/x-www-form-urlencoded'25CONTENT_TYPE_MULTI_PART = 'multipart/form-data'262728def _basic_auth_str(username, password):29 """Returns a Basic Auth string."""3031 # "I want us to put a big-ol' comment on top of it that32 # says that this behaviour is dumb but we need to preserve33 # it because people are relying on it."34 # - Lukasa35 #36 # These are here solely to maintain backwards compatibility37 # for things like ints. This will be removed in 3.0.0.38 if not isinstance(username, basestring):39 warnings.warn(40 "Non-string usernames will no longer be supported in Requests "Merge pull request #4835 from requests/2.20.0Nate Prewittbefore adoption75bdc99
line 41why, one step back41 "3.0.0. Please convert the object you've passed in ({!r}) to "Merge pull request #4749 from derlin/masterNate Prewittbefore adoptione4d214d
lines 42–50why, one step back42 "a string or bytes object in the near future to avoid "43 "problems.".format(username),44 category=DeprecationWarning,45 )46 username = str(username)4748 if not isinstance(password, basestring):49 warnings.warn(50 "Non-string passwords will no longer be supported in Requests "Merge pull request #4835 from requests/2.20.0Nate Prewittbefore adoption75bdc99
line 51why, one step back51 "3.0.0. Please convert the object you've passed in ({!r}) to "Merge pull request #4749 from derlin/masterNate Prewittbefore adoptione4d214d
line 52why, one step back52 "a string or bytes object in the near future to avoid "Merge pull request #5099 from petar-iv/password-no-printBuğra İşgüzarbefore adoption6f81e78
line 53why, one step back53 "problems.".format(type(password)),Merge pull request #4749 from derlin/masterNate Prewittbefore adoptione4d214d
lines 54–241why, one step back54 category=DeprecationWarning,55 )56 password = str(password)57 # -- End Removal --5859 if isinstance(username, str):60 username = username.encode('latin1')6162 if isinstance(password, str):63 password = password.encode('latin1')6465 authstr = 'Basic ' + to_native_string(66 b64encode(b':'.join((username, password))).strip()67 )6869 return authstr707172class AuthBase(object):73 """Base class that all auth implementations derive from"""7475 def __call__(self, r):76 raise NotImplementedError('Auth hooks must be callable.')777879class HTTPBasicAuth(AuthBase):80 """Attaches HTTP Basic Authentication to the given Request object."""8182 def __init__(self, username, password):83 self.username = username84 self.password = password8586 def __eq__(self, other):87 return all([88 self.username == getattr(other, 'username', None),89 self.password == getattr(other, 'password', None)90 ])9192 def __ne__(self, other):93 return not self == other9495 def __call__(self, r):96 r.headers['Authorization'] = _basic_auth_str(self.username, self.password)97 return r9899100class HTTPProxyAuth(HTTPBasicAuth):101 """Attaches HTTP Proxy Authentication to a given Request object."""102103 def __call__(self, r):104 r.headers['Proxy-Authorization'] = _basic_auth_str(self.username, self.password)105 return r106107108class HTTPDigestAuth(AuthBase):109 """Attaches HTTP Digest Authentication to the given Request object."""110111 def __init__(self, username, password):112 self.username = username113 self.password = password114 # Keep state in per-thread local storage115 self._thread_local = threading.local()116117 def init_per_thread_state(self):118 # Ensure state is initialized just once per-thread119 if not hasattr(self._thread_local, 'init'):120 self._thread_local.init = True121 self._thread_local.last_nonce = ''122 self._thread_local.nonce_count = 0123 self._thread_local.chal = {}124 self._thread_local.pos = None125 self._thread_local.num_401_calls = None126127 def build_digest_header(self, method, url):128 """129 :rtype: str130 """131132 realm = self._thread_local.chal['realm']133 nonce = self._thread_local.chal['nonce']134 qop = self._thread_local.chal.get('qop')135 algorithm = self._thread_local.chal.get('algorithm')136 opaque = self._thread_local.chal.get('opaque')137 hash_utf8 = None138139 if algorithm is None:140 _algorithm = 'MD5'141 else:142 _algorithm = algorithm.upper()143 # lambdas assume digest modules are imported at the top level144 if _algorithm == 'MD5' or _algorithm == 'MD5-SESS':145 def md5_utf8(x):146 if isinstance(x, str):147 x = x.encode('utf-8')148 return hashlib.md5(x).hexdigest()149 hash_utf8 = md5_utf8150 elif _algorithm == 'SHA':151 def sha_utf8(x):152 if isinstance(x, str):153 x = x.encode('utf-8')154 return hashlib.sha1(x).hexdigest()155 hash_utf8 = sha_utf8156 elif _algorithm == 'SHA-256':157 def sha256_utf8(x):158 if isinstance(x, str):159 x = x.encode('utf-8')160 return hashlib.sha256(x).hexdigest()161 hash_utf8 = sha256_utf8162 elif _algorithm == 'SHA-512':163 def sha512_utf8(x):164 if isinstance(x, str):165 x = x.encode('utf-8')166 return hashlib.sha512(x).hexdigest()167 hash_utf8 = sha512_utf8168169 KD = lambda s, d: hash_utf8("%s:%s" % (s, d))170171 if hash_utf8 is None:172 return None173174 # XXX not implemented yet175 entdig = None176 p_parsed = urlparse(url)177 #: path is request-uri defined in RFC 2616 which should not be empty178 path = p_parsed.path or "/"179 if p_parsed.query:180 path += '?' + p_parsed.query181182 A1 = '%s:%s:%s' % (self.username, realm, self.password)183 A2 = '%s:%s' % (method, path)184185 HA1 = hash_utf8(A1)186 HA2 = hash_utf8(A2)187188 if nonce == self._thread_local.last_nonce:189 self._thread_local.nonce_count += 1190 else:191 self._thread_local.nonce_count = 1192 ncvalue = '%08x' % self._thread_local.nonce_count193 s = str(self._thread_local.nonce_count).encode('utf-8')194 s += nonce.encode('utf-8')195 s += time.ctime().encode('utf-8')196 s += os.urandom(8)197198 cnonce = (hashlib.sha1(s).hexdigest()[:16])199 if _algorithm == 'MD5-SESS':200 HA1 = hash_utf8('%s:%s:%s' % (HA1, nonce, cnonce))201202 if not qop:203 respdig = KD(HA1, "%s:%s" % (nonce, HA2))204 elif qop == 'auth' or 'auth' in qop.split(','):205 noncebit = "%s:%s:%s:%s:%s" % (206 nonce, ncvalue, cnonce, 'auth', HA2207 )208 respdig = KD(HA1, noncebit)209 else:210 # XXX handle auth-int.211 return None212213 self._thread_local.last_nonce = nonce214215 # XXX should the partial digests be encoded too?216 base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \217 'response="%s"' % (self.username, realm, nonce, path, respdig)218 if opaque:219 base += ', opaque="%s"' % opaque220 if algorithm:221 base += ', algorithm="%s"' % algorithm222 if entdig:223 base += ', digest="%s"' % entdig224 if qop:225 base += ', qop="auth", nc=%s, cnonce="%s"' % (ncvalue, cnonce)226227 return 'Digest %s' % (base)228229 def handle_redirect(self, r, **kwargs):230 """Reset num_401_calls counter on redirects."""231 if r.is_redirect:232 self._thread_local.num_401_calls = 1233234 def handle_401(self, r, **kwargs):235 """236 Takes the given response and tries digest-auth, if needed.237238 :rtype: requests.Response239 """240241 # If response is not 4xx, do not authMerge pull request #5160 from OrangutanGaming/change-githubNate Prewittbefore adoptiond79024f
line 242why, one step back242 # See https://github.com/psf/requests/issues/3772Merge pull request #4749 from derlin/masterNate Prewittbefore adoptione4d214d
lines 243–305why, one step back243 if not 400 <= r.status_code < 500:244 self._thread_local.num_401_calls = 1245 return r246247 if self._thread_local.pos is not None:248 # Rewind the file position indicator of the body to where249 # it was to resend the request.250 r.request.body.seek(self._thread_local.pos)251 s_auth = r.headers.get('www-authenticate', '')252253 if 'digest' in s_auth.lower() and self._thread_local.num_401_calls < 2:254255 self._thread_local.num_401_calls += 1256 pat = re.compile(r'digest ', flags=re.IGNORECASE)257 self._thread_local.chal = parse_dict_header(pat.sub('', s_auth, count=1))258259 # Consume content and release the original connection260 # to allow our new request to reuse the same one.261 r.content262 r.close()263 prep = r.request.copy()264 extract_cookies_to_jar(prep._cookies, r.request, r.raw)265 prep.prepare_cookies(prep._cookies)266267 prep.headers['Authorization'] = self.build_digest_header(268 prep.method, prep.url)269 _r = r.connection.send(prep, **kwargs)270 _r.history.append(r)271 _r.request = prep272273 return _r274275 self._thread_local.num_401_calls = 1276 return r277278 def __call__(self, r):279 # Initialize per-thread state, if needed280 self.init_per_thread_state()281 # If we have a saved nonce, skip the 401282 if self._thread_local.last_nonce:283 r.headers['Authorization'] = self.build_digest_header(r.method, r.url)284 try:285 self._thread_local.pos = r.body.tell()286 except AttributeError:287 # In the case of HTTPDigestAuth being reused and the body of288 # the previous request was a file-like object, pos has the289 # file position of the previous body. Ensure it's set to290 # None.291 self._thread_local.pos = None292 r.register_hook('response', self.handle_401)293 r.register_hook('response', self.handle_redirect)294 self._thread_local.num_401_calls = 1295296 return r297298 def __eq__(self, other):299 return all([300 self.username == getattr(other, 'username', None),301 self.password == getattr(other, 'password', None)302 ])303304 def __ne__(self, other):305 return not self == other