Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add OAuth2 support #792

Open
arondaniel opened this issue Dec 5, 2023 · 1 comment
Open

Add OAuth2 support #792

arondaniel opened this issue Dec 5, 2023 · 1 comment

Comments

@arondaniel
Copy link

arondaniel commented Dec 5, 2023

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

@mpenkov
Copy link
Collaborator

mpenkov commented Feb 8, 2024

Are you interested in doing a PR?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants