Add OAuth2 support
Problem description
It would be nice to use smart_open to access OAuth2 URLs. In my case I needed to access resources using NASA URS.
I'm new to this library but I couldn't find a way to make this work directly using your API (without registering a new http/https handler).
I was able to make it work pretty easily by passing in my own requests.Session object into the http.py open method and storing that in the io.BufferedIOBase subclasses. Then, I just use that Session object in the two "get" calls if it's not None.
The Session object I used worked for me. Not sure if it works for other OAuth hosts:
class URSSession(requests.Session):
auth_host = None
def __init__(self, auth_host, username, password):
super().__init__()
self.auth_host = auth_host
self.auth = (username, password)
# Overrides from the library to keep headers when redirected to or from
# the NASA auth host.
def rebuild_auth(self, prepared_request, response):
headers = prepared_request.headers
url = prepared_request.url
if 'Authorization' in headers:
original_parsed = requests.utils.urlparse(response.request.url)
redirect_parsed = requests.utils.urlparse(url)
if (original_parsed.hostname != redirect_parsed.hostname) and \
redirect_parsed.hostname != self.auth_host and \
original_parsed.hostname != self.auth_host:
del headers['Authorization']
return
So... if others may want to do this, maybe it would be good to make http handler take an optional requests.Session?
Steps/code to reproduce the problem
None, just a suggestion for improvement.
Versions
macOS-12.6.7-arm64-arm-64bit Python 3.10.11 | packaged by conda-forge | (main, May 10 2023, 19:01:19) [Clang 14.0.6 ] smart_open 6.4.0
Are you interested in doing a PR?