Skip to content
Myr

Issue #2334 - HTTPAuthDigest - Making it thread-safe

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

The existing code counts the number of 401 responses in the num_401_calls authenticator attribute. This is in place so as to ensure the necessary auth header is sent, while avoiding infinite 401 loops (issue #547). This commit makes num_401_calls an instance of threading.local() (previously an integer), using num_401_calls.value as the counter. It ensures that concurrent authentication requests get each their own counter and behave as expected (otherwise every other concurrent request would have its authentication fail).

authored by exvito · committed by exvito · parent 0ad075c · Browse files · 1 file+8 added−5 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+8 added−5 removed

  • other:+8 added−5 removed

1 file+8 added−5 removed

modified:requests/auth.py+8 added-5 removed
9 unmodified lines
10import os11import re12import time13import hashlib14import threading1516from base64 import b64encode1718from .compat import urlparse, str
48 unmodified lines
67 self.last_nonce = ''68 self.nonce_count = 069 self.chal = {}70 self.pos = None70 self.num_401_calls = 171 self.num_401_calls = threading.local()7273 def build_digest_header(self, method, url):7475 realm = self.chal['realm']
81 unmodified lines
157158 def handle_redirect(self, r, **kwargs):159 """Reset num_401_calls counter on redirects."""160 if r.is_redirect:160 self.num_401_calls = 1161 self.num_401_calls.value = 1162163 def handle_401(self, r, **kwargs):164 """Takes the given response and tries digest-auth, if needed."""165166 if self.pos is not None:167 # Rewind the file position indicator of the body to where168 # it was to resend the request.169 r.request.body.seek(self.pos)169 num_401_calls = getattr(self, 'num_401_calls', 1)170 num_401_calls = getattr(self.num_401_calls, 'value', 1)171 s_auth = r.headers.get('www-authenticate', '')172173 if 'digest' in s_auth.lower() and num_401_calls < 2:174174 self.num_401_calls += 1175 self.num_401_calls.value += 1176 pat = re.compile(r'digest ', flags=re.IGNORECASE)177 self.chal = parse_dict_header(pat.sub('', s_auth, count=1))178179 # Consume content and release the original connection
11 unmodified lines
191 _r.request = prep192193 return _r194194 self.num_401_calls = 1195 self.num_401_calls.value = 1196 return r197198 def __call__(self, r):199 # If we have a saved nonce, skip the 401
8 unmodified lines
208 # None.209 self.pos = None210 r.register_hook('response', self.handle_401)211 r.register_hook('response', self.handle_redirect)212 self.num_401_calls.value = 1213214 return r