From: Cory Benfield Date: Wed, 12 Mar 2014 19:22:11 +0000 (+0000) Subject: Move auth rebuild to its own method. X-Git-Tag: v2.3.0~27^2^2~4 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=97cf16e958a948ecf30c3019ae94f2e7ec7dcb7f;p=services%2Fpython-requests.git Move auth rebuild to its own method. --- diff --git a/requests/sessions.py b/requests/sessions.py index 425db22..4c24984 100644 --- a/requests/sessions.py +++ b/requests/sessions.py @@ -154,19 +154,7 @@ class SessionRedirectMixin(object): prepared_request._cookies.update(self.cookies) prepared_request.prepare_cookies(prepared_request._cookies) - if 'Authorization' in headers: - # If we get redirected to a new host, we should strip out any - # authentication headers. - original_parsed = urlparse(resp.request.url) - redirect_parsed = urlparse(url) - - if (original_parsed.hostname != redirect_parsed.hostname): - del headers['Authorization'] - - # .netrc might have more auth for us. - new_auth = get_netrc_auth(url) if self.trust_env else None - if new_auth is not None: - prepared_request.prepare_auth(new_auth) + self.rebuild_auth(prepared_request, resp) resp = self.send( prepared_request, @@ -183,6 +171,31 @@ class SessionRedirectMixin(object): i += 1 yield resp + def rebuild_auth(self, prepared_request, response): + """ + When being redirected we may want to strip authentication from the + request to avoid leaking credentials. This method intelligently removes + and reapplies authentication where possible to avoid credential loss. + """ + headers = prepared_request.headers + url = prepared_request.url + + if 'Authorization' in headers: + # If we get redirected to a new host, we should strip out any + # authentication headers. + original_parsed = urlparse(response.request.url) + redirect_parsed = urlparse(url) + + if (original_parsed.hostname != redirect_parsed.hostname): + del headers['Authorization'] + + # .netrc might have more auth for us on our new host. + new_auth = get_netrc_auth(url) if self.trust_env else None + if new_auth is not None: + prepared_request.prepare_auth(new_auth) + + return + class Session(SessionRedirectMixin): """A Requests session.