Start work on sending cookies back
authorIan Ross and Ian Cordasco <dev+iross+sigmavirus24@bendyworks.com>
Fri, 19 Jul 2013 20:13:28 +0000 (15:13 -0500)
committerIan Cordasco <graffatcolmingov@gmail.com>
Sun, 28 Jul 2013 03:07:25 +0000 (23:07 -0400)
On 401's the cookies received aren't sent back to the server. See: #1336

requests/auth.py
test_requests.py

index fab05cf..665b1db 100644 (file)
@@ -18,7 +18,6 @@ from base64 import b64encode
 from .compat import urlparse, str
 from .utils import parse_dict_header
 
-
 log = logging.getLogger(__name__)
 
 CONTENT_TYPE_FORM_URLENCODED = 'application/x-www-form-urlencoded'
@@ -146,6 +145,7 @@ class HTTPDigestAuth(AuthBase):
     def handle_401(self, r, **kwargs):
         """Takes the given response and tries digest-auth, if needed."""
 
+        from .models import PreparedRequest
         num_401_calls = getattr(self, 'num_401_calls', 1)
         s_auth = r.headers.get('www-authenticate', '')
 
@@ -159,10 +159,17 @@ class HTTPDigestAuth(AuthBase):
             # to allow our new request to reuse the same one.
             r.content
             r.raw.release_conn()
+            prepared_request = PreparedRequest()
+            prepared_request.url = r.request.url
+            prepared_request.body = r.request.body
+            prepared_request.headers = r.request.headers.copy()
+            prepared_request.hooks = r.request.hooks
+            prepared_request.prepare_cookies(r.cookies)
 
             r.request.headers['Authorization'] = self.build_digest_header(r.request.method, r.request.url)
-            _r = r.connection.send(r.request, **kwargs)
+            _r = r.connection.send(prepared_request, **kwargs)
             _r.history.append(r)
+            _r.request = prepared_request
 
             return _r
 
index 27d5e67..756bc87 100755 (executable)
@@ -289,6 +289,22 @@ class RequestsTestCase(unittest.TestCase):
         r = s.get(url)
         self.assertEqual(r.status_code, 200)
 
+    def test_DIGEST_AUTH_RETURNS_COOKIE(self):
+        url = httpbin('digest-auth', 'auth', 'user', 'pass')
+        auth = HTTPDigestAuth('user', 'pass')
+        r = requests.get(url)
+        assert r.cookies['fake'] == 'fake_value'
+
+        r = requests.get(url, auth=auth)
+        assert r.status_code == 200
+
+    def test_DIGEST_AUTH_SETS_SESSION_COOKIES(self):
+        url = httpbin('digest-auth', 'auth', 'user', 'pass')
+        auth = HTTPDigestAuth('user', 'pass')
+        s = requests.Session()
+        s.get(url, auth=auth)
+        assert s.cookies['fake'] == 'fake_value'
+
     def test_DIGEST_STREAM(self):
 
         auth = HTTPDigestAuth('user', 'pass')