Save credentials in the HTTPDigestAuth object and replay them if the user reuses the object.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Peter Montagner · committed by Peter Montagner · parent 53d454c · Browse files · 1 file·+82 added−74 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
1 file+82 added−74 removed
- other:+82 added−74 removed
Provenance
- Commit
5017aeb- Tree
4a1a57d- Author
Peter Montagner <zigmonty@gmail.com>- Committer
Peter Montagner <zigmonty@gmail.com>- Parent
53d454c
1 file changed+82 added−74 removed
modified:requests/auth.py+82 added-74 removed
141 unmodified lines142 """Attaches HTTP Digest Authentication to the given Request object."""143 def __init__(self, username, password):144 self.username = username145 self.password = password146+ self.last_nonce = ''147+ self.nonce_count = 0148+ self.chal = {}149 150+ def build_digest_header(self, method, url):151+152+ realm = self.chal['realm']153+ nonce = self.chal['nonce']154+ qop = self.chal.get('qop')155+ algorithm = self.chal.get('algorithm', 'MD5')156+ opaque = self.chal.get('opaque', None)157+ 158+ algorithm = algorithm.upper()159+ # lambdas assume digest modules are imported at the top level160+ if algorithm == 'MD5':161+ def md5_utf8(x):162+ if isinstance(x, str):163+ x = x.encode('utf-8')164+ return hashlib.md5(x).hexdigest()165+ hash_utf8 = md5_utf8166+ elif algorithm == 'SHA':167+ def sha_utf8(x):168+ if isinstance(x, str):169+ x = x.encode('utf-8')170+ return hashlib.sha1(x).hexdigest()171+ hash_utf8 = sha_utf8172+ # XXX MD5-sess173+ KD = lambda s, d: hash_utf8("%s:%s" % (s, d))174+ 175+ if hash_utf8 is None:176+ return None177+ 178+ # XXX not implemented yet179+ entdig = None180+ p_parsed = urlparse(url)181+ path = p_parsed.path182+ if p_parsed.query:183+ path += '?' + p_parsed.query184+ 185+ A1 = '%s:%s:%s' % (self.username, realm, self.password)186+ A2 = '%s:%s' % (method, path)187+ 188+ if qop == 'auth':189+ if nonce == self.last_nonce:190+ self.nonce_count += 1191+ else:192+ self.nonce_count = 1193+ 194+ ncvalue = '%08x' % self.nonce_count195+ s = str(self.nonce_count).encode('utf-8')196+ s += nonce.encode('utf-8')197+ s += time.ctime().encode('utf-8')198+ s += os.urandom(8)199+ 200+ cnonce = (hashlib.sha1(s).hexdigest()[:16])201+ noncebit = "%s:%s:%s:%s:%s" % (nonce, ncvalue, cnonce, qop, hash_utf8(A2))202+ respdig = KD(hash_utf8(A1), noncebit)203+ elif qop is None:204+ respdig = KD(hash_utf8(A1), "%s:%s" % (nonce, hash_utf8(A2)))205+ else:206+ # XXX handle auth-int.207+ return None208+ 209+ self.last_nonce = nonce210+ 211+ # XXX should the partial digests be encoded too?212+ base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \213+ 'response="%s"' % (self.username, realm, nonce, path, respdig)214+ if opaque:215+ base += ', opaque="%s"' % opaque216+ if entdig:217+ base += ', digest="%s"' % entdig218+ base += ', algorithm="%s"' % algorithm219+ if qop:220+ base += ', qop=auth, nc=%s, cnonce="%s"' % (ncvalue, cnonce)221+ 222+ return 'Digest %s' % (base)223+224 def handle_401(self, r):225 """Takes the given response and tries digest-auth, if needed."""226 227 num_401_calls = r.request.hooks['response'].count(self.handle_401)1 unmodified line229 s_auth = r.headers.get('www-authenticate', '')230 231 if 'digest' in s_auth.lower() and num_401_calls < 2:232 156- last_nonce = ''157- nonce_count = 0233+ self.chal = parse_dict_header(s_auth.replace('Digest ', ''))234 159- chal = parse_dict_header(s_auth.replace('Digest ', ''))160-161- realm = chal['realm']162- nonce = chal['nonce']163- qop = chal.get('qop')164- algorithm = chal.get('algorithm', 'MD5')165- opaque = chal.get('opaque', None)166-167- algorithm = algorithm.upper()168- # lambdas assume digest modules are imported at the top level169- if algorithm == 'MD5':170- def md5_utf8(x):171- if isinstance(x, str):172- x = x.encode('utf-8')173- return hashlib.md5(x).hexdigest()174- hash_utf8 = md5_utf8175- elif algorithm == 'SHA':176- def sha_utf8(x):177- if isinstance(x, str):178- x = x.encode('utf-8')179- return hashlib.sha1(x).hexdigest()180- hash_utf8 = sha_utf8181- # XXX MD5-sess182- KD = lambda s, d: hash_utf8("%s:%s" % (s, d))183-184- if hash_utf8 is None:185- return None186-187- # XXX not implemented yet188- entdig = None189- p_parsed = urlparse(r.request.url)190- path = p_parsed.path191- if p_parsed.query:192- path += '?' + p_parsed.query193-194- A1 = '%s:%s:%s' % (self.username, realm, self.password)195- A2 = '%s:%s' % (r.request.method, path)196-197- if qop == 'auth':198- if nonce == last_nonce:199- nonce_count += 1200- else:201- nonce_count = 1202- last_nonce = nonce203-204- ncvalue = '%08x' % nonce_count205- s = str(nonce_count).encode('utf-8')206- s += nonce.encode('utf-8')207- s += time.ctime().encode('utf-8')208- s += os.urandom(8)209-210- cnonce = (hashlib.sha1(s).hexdigest()[:16])211- noncebit = "%s:%s:%s:%s:%s" % (nonce, ncvalue, cnonce, qop, hash_utf8(A2))212- respdig = KD(hash_utf8(A1), noncebit)213- elif qop is None:214- respdig = KD(hash_utf8(A1), "%s:%s" % (nonce, hash_utf8(A2)))215- else:216- # XXX handle auth-int.217- return None218-219- # XXX should the partial digests be encoded too?220- base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \221- 'response="%s"' % (self.username, realm, nonce, path, respdig)222- if opaque:223- base += ', opaque="%s"' % opaque224- if entdig:225- base += ', digest="%s"' % entdig226- base += ', algorithm="%s"' % algorithm227- if qop:228- base += ', qop=auth, nc=%s, cnonce="%s"' % (ncvalue, cnonce)229-235 # Consume content and release the original connection 236 # to allow our new request to reuse the same one.237 r.content238 r.raw.release_conn()239 235- r.request.headers['Authorization'] = 'Digest %s' % (base)240+ r.request.headers['Authorization'] = self.build_digest_header(r.request.method, r.request.url)241 r.request.send(anyway=True)242 _r = r.request.response243 _r.history.append(r)244 1 unmodified line246 247 return r248 249 def __call__(self, r):250+ # If we have a saved nonce, skip the 401251+ if self.last_nonce:252+ r.headers['Authorization'] = self.build_digest_header(r.method, r.url) 253 r.register_hook('response', self.handle_401)254 return r255 256 121 unmodified lines