Giter VIP home page Giter VIP logo

google-auth-library-python-oauthlib's Introduction

oauthlib integration for Google Auth

pypi

This library provides oauthlib integration with google-auth.

Installing

You can install using pip:

$ pip install google-auth-oauthlib

Documentation

The latest documentation is available at google-auth-oauthlib.googleapis.dev.

Supported Python Versions

Python >= 3.6

Unsupported Python Versions

Python == 2.7, Python == 3.5.

The last version of this library compatible with Python 2.7 and 3.5 is google-auth-oauthlib==0.4.1.

License

Apache 2.0 - See the LICENSE for more information.

google-auth-library-python-oauthlib's People

Contributors

andytzeng avatar arithmetic1728 avatar busunkim96 avatar clundin25 avatar dandhlee avatar gcf-owl-bot[bot] avatar gilesknap avatar google-cloud-policy-bot[bot] avatar jay0lee avatar justinbeckwith avatar keriwarr avatar markmcd avatar mgorny avatar michelts avatar ngklingler avatar nicain avatar parthea avatar proppy avatar rahularanger avatar release-please[bot] avatar renovate-bot avatar sai-sunder-s avatar scruffyprodigy avatar sqrrrl avatar surferjeffatgoogle avatar tswast avatar viicos avatar wchargin avatar wescande avatar wonggw avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

google-auth-library-python-oauthlib's Issues

run_console() broken

Environment details

  • Docker Image: tensorflow/tensorflow:2.3.0-gpu
  • Python version: 3.6.9
  • pip version: 20.1.1
  • google-auth-oauthlib version: 0.4.2

Code example

google_auth_oauthlib.get_user_credentials(scopes, config['installed']['client_id'], config['installed']['client_secret'])

Stack trace

Enter the authorization code: Traceback (most recent call last):
  File "/usr/lib/python3.6/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/usr/lib/python3.6/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/code/src/main.py", line 71, in <module>
    main(sys.argv[1:])
  File "/code/src/main.py", line 50, in main
    handle_drive = IODriveData()
  File "/code/src/data/io_drive_data.py", line 39, in __init__
    self.service = _auth_drive()
  File "/code/src/data/io_drive_data.py", line 27, in _auth_drive
    creds = google_auth_oauthlib.get_user_credentials(scopes, config['installed']['client_id'], config['installed']['client_secret'])
  File "/usr/local/lib/python3.6/dist-packages/google_auth_oauthlib/interactive.py", line 105, in get_user_credentials
    return app_flow.run_console()
  File "/usr/local/lib/python3.6/dist-packages/google_auth_oauthlib/flow.py", line 412, in run_console
    code = input(authorization_code_message)
EOFError: EOF when reading a line```

run_local_server not works on heroku

Hi, I have a project running on heroku, I'm trying to authenticate with Google API, but It doesn't open the new window, it works fine on my localhost. Does anyone know how to fix this?
Thanks

            flow = InstalledAppFlow.from_client_config(credentials, SCOPES)
            creds = flow.run_local_server(port=0)

run_local_server should fail fast if the requested port is already used

The following script fails poorly by hanging indefinitely. I believe this is because the token actually gets sent to SimpleHTTPRequestHandler, not the oauth flow server.

import http.server
import socketserver
import threading
import time

from google_auth_oauthlib import flow


CLIENT_ID = ...
CLIENT_SECRET = ...
GOOGLE_AUTH_URI = "https://accounts.google.com/o/oauth2/auth"
GOOGLE_TOKEN_URI = "https://oauth2.googleapis.com/token"


def occupy_port():
    # Create an HTTP server to take up port 8080.
    Handler = http.server.SimpleHTTPRequestHandler
    with socketserver.TCPServer(("", 8080), Handler) as httpd:
        httpd.serve_forever()

server = threading.Thread(target=occupy_port)
server.start()
time.sleep(2)

client_config = {
    "installed": {
        "client_id": CLIENT_ID,
        "client_secret": CLIENT_SECRET,
        "redirect_uris": ["urn:ietf:wg:oauth:2.0:oob"],
        "auth_uri": GOOGLE_AUTH_URI,
        "token_uri": GOOGLE_TOKEN_URI,
    }
}
app_flow = flow.InstalledAppFlow.from_client_config(
    client_config, scopes=["https://www.googleapis.com/auth/cloud-platform"]
)
credentials = app_flow.run_local_server(port=8080)
assert credentials is not None

server.join(timeout=1)

Instead, I would expect run_local_server to fail fast (don't open the browser window) due to occupied port. For example, socketserver raises OSError: [Errno 48] Address already in use. I'd expect something similar (or a more specific exception) from google-auth-oauthlib.

google-cloud-sdk still uses deprecated oauth2client?

I'm getting the following error on Ubuntu-16.04:

Setting up google-cloud-sdk (182.0.0-0) ...
Compiling lib/third_party/oauth2client/contrib/reauth_creds.py ...
Sorry: IndentationError: unindent does not match any outer indentation level (reauth_creds.py, line 136)

Installing with:

export CLOUD_SDK_REPO="cloud-sdk-$(lsb_release -c -s)"
echo "deb http://packages.cloud.google.com/apt $CLOUD_SDK_REPO main" | sudo tee -a /etc/apt/sources.list.d/google-cloud-sdk.list
curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -
sudo apt-get update && sudo apt-get install google-cloud-sdk

googleapis/oauth2client#732

Tests do not run in python3

Looks like something is up with the mocking code.

e.g. (there are many failures, this is the first)

=================================== FAILURES ===================================
____________________ TestInstalledAppFlow.test_run_console _____________________

args = (<....google_auth_oauthlib.tests.test_flow.TestInstalledAppFlow object at 0x7f5a9d29f1d0>,)
keywargs = {'instance': <google_auth_oauthlib.flow.InstalledAppFlow object at 0x7f5a9d29f978>, 'mock_fetch_token': <function fetch_token at 0x7f5a9d29a9d8>}
extra_args = [], entered_patchers = []
exc_info = (<class 'AttributeError'>, AttributeError("'method-wrapper' object has no attribute '__module__'",), <traceback object at 0x7f5a9d2975c8>)
patching = <mock._patch object at 0x7f5a9cf501d0>

    @wraps(func)
    def patched(*args, **keywargs):
        # don't use a with here (backwards compatability with Python 2.4)
        extra_args = []
        entered_patchers = []
    
        # can't use try...except...finally because of Python 2.4
        # compatibility
        exc_info = tuple()
        try:
            try:
                for patching in patched.patchings:
>                   arg = patching.__enter__()

.../py/mock/__init__.py:1244: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
.../py/mock/__init__.py:1400: in __enter__
    _name=self.attribute, **kwargs)
.../py/mock/__init__.py:2244: in create_autospec
    _check_signature(spec, mock, is_type, instance)
.../py/mock/__init__.py:202: in _check_signature
    _copy_func_details(func, checksig)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

func = <method-wrapper '__call__' of builtin_function_or_method object at 0x7f5a9f8dbc18>
funcopy = <function <lambda> at 0x7f5a9d2e9620>

    def _copy_func_details(func, funcopy):
        funcopy.__name__ = func.__name__
        funcopy.__doc__ = func.__doc__
        #funcopy.__dict__.update(func.__dict__)
>       funcopy.__module__ = func.__module__
E       AttributeError: 'method-wrapper' object has no attribute '__module__'

.../py/mock/__init__.py:210: AttributeError

wsgi_app.last_request_uri has no attribute 'replace'

Hi,

I have an issue running Google API Quickstart:

Traceback (most recent call last):
  File "quickstart.py", line 49, in <module>
    main() 
  File "quickstart.py", line 29, in main
    creds = flow.run_local_server(port=0)
  File "/usr/lib/python3.8/site-packages/google_auth_oauthlib/flow.py", line 458, in run_local_server
    authorization_response = wsgi_app.last_request_uri.replace('http', 'https')
AttributeError: 'NoneType' object has no attribute 'replace'

Am I doing something wrong?

How can I autopass Google Calendar API authorization on Android Things?

As I see your library could be used for auto passing OAuth authorization on Android Things. It's used in this project for Google Assistant API - https://github.com/androidthings/sample-googleassistant.

I'm curious if it's possible to do the similar things for Google Calendar API authorizatoin. So in other words, is it possible to auto pass Google Calendar API authorization on Android Things device using your library?

Thanks!

Passing `code_verifier` argument from `Flow.from_client_config()` to class constructor is missing.

With the introduction of code_verifier it should be possible to pass our own code_verifier to Flow.from_client_config() classmethod.

Currently, if you pass it as kwargs, the requests_oauth session creation will fail because code_verifier is not supposed to be in kwargs for that class and if it didn't, the value itself would not be passed to the constructor.

I think it would be a good idea to include code_verifier as a positional argument for the from_client_config() function.

change from oauth2client

Hi there,
I am new to oauth2 and changing oauth2client-related code to google_auth_oauthlib since the former is deprecated now.
Our private website compares a user's google+ id with our stored google+ ids to decide whether to give access.
However id_token of the two are different types with different info and I don't find a way to access google+ id (gplus_id) using your Credentials object. The two versions of codes are basically as follows. Could you please help with this?

oauth2client version

http://oauth2client.readthedocs.io/en/latest/_modules/oauth2client/client.html#OAuth2Credentials

from oauth2client.client import flow_from_clientsecrets
@app.route('/connect', methods=['POST'])
def connect():
    code= request.data
    oauth_flow = flow_from_clientsecrets("client_secrets.json", scope='')
    oauth_flow.redirect_uri = 'postmessage'
    credentials = oauth_flow.step2_exchange(code)
    gplus_id = credentials.id_token['sub']

google_auth_oauthlib trial version

http://google-auth.readthedocs.io/en/latest/_modules/google/oauth2/credentials.html#Credentials

import google_auth_oauthlib.flow
@app.route('/connect', methods=['POST'])
def connect():
    code = request.data
    flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file('client_secrets.json', scopes='')
    flow.redirect_uri = 'postmessage'
    flow.fetch_token(code=code)
    credentials = flow.credentials

Thank you.

Display given success message when handle the authorization redirect as unicode string.

Hello.

In case if success message text contains unicode characters, for example:
success_message = 'El flujo de autenticación se ha completado. Puede cerrar esta ventana.'
in browser this text is displayed as:
El flujo de autenticación se ha completado. Puede cerrar esta ventana.

I propose make change in line google_auth_oauthlib/flow.py:522:
return [self._success_message.encode("utf-8")]
to
return [self._success_message.encode("raw_unicode_escape")]

Scopes are incorrectly documented as Sequence[str] type in flow.py

In flow.py, scopes are incorrectly documented as Sequence[str] in the classmethod documentation.

As far as I can tell, following the code path back up to oauthlib, scopes ends up being passed to the scope_to_list helper function which can actually take scopes in the format of list, tuple, set, str.

Importantly, set is not considered a sequence, but is useful in the context of scopes - you may have multiple tasks wishing to add to a set of scopes, in which case using set avoids unnecessary duplicates.

Suggestion: Change to Union[list[str], tuple[str], set[str], str] or Union[list[str], tuple[str], set[str]] instead.

I ran the project test** file, but the operation returned without result

I ran the project test** file, but the operation returned without result

May I ask if there is a more detailed tutorial?

Did I make a configuration error?

{
"installed": {
"client_id": "806572844570-3iv5loac0v8rl01b3pia5apq92tvdtjb.apps.googleusercontent.com",
"project_id": "magicdemo-179609",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"redirect_uris": [
"urn:ietf:wg:oauth:2.0:oob",
"http://localhost"
]
}
}

`code_verify` is not automatically generated if not passed as an argument.

In our system we have several private API endpoints that we use for user authentication.

When a user gets /api/authenticate the following function is executed:

def authenticate_user(self):
    """Redirects a user to Google to authenticate them."""
    session, client_config = google_auth_oauthlib.helpers.session_from_client_config(
        self._client_config,
        self._scopes
    )
    flow = google_auth_oauthlib.flow.Flow(
        session,
        'web',
        client_config,
        recirect_uri=flask.url_for('user_login_callback', _external=True),
    )

    authorization_url, state = flow.authorization_url(
        access_type='offline',
        include_granted_scopes='true',
        hd='avast.com'
    )
    flask.session['state'] = state

    return flask.redirect(authorization_url)

Which will redirect the user to our verification routine:

def verify_authentication(self):
    """Called when redirected from Google to save the credentials into session."""
    state = flask.session['state']
    session, client_config = google_auth_oauthlib.helpers.session_from_client_config(
        self._client_config,
        self._scopes,
        state=state
    )
    flow = google_auth_oauthlib.flow.Flow(
        session,
        'web',
        client_config,
        recirect_uri=flask.url_for('user_login_callback', _external=True),
    )

    flow.fetch_token(authorization_response=flask.request.url)
    ...

Before the introduction of code_verifier the aforementioned code worked flawlessly. The problem here, is that the flow.fetch_token() method is trying to use code_verifier, but the value of it is never generated, so the call will fail with oauthlib.oauth2.rfc6749.errors.InvalidGrantError: (invalid_grant) Missing code verifier.

Is this behaviour expected? If so, should the flow be somehow stored between authentication attempt and verification (i.e. in session)?

Allow storing previously authenticated credentials to speed up flow.

Similar to functionality found in oauth2client, it would be nice to have a way to automatically store credentials verified through a Flow. This could be used to easily check in future if a user needs to run through the process again. Below usage example from here.

storage = file.Storage('analyticsreporting.dat')
credentials = storage.get()
if credentials is None or credentials.invalid:
    credentials = tools.run_flow(flow, storage, flags)
http = credentials.authorize(http=httplib2.Http())

self._quota_project_id Error on credentials

I'm having problem to use this lib on ubuntu server, some how the lib doenst work. my code runs in windows10, ubuntu desktop 18.04, but when I try to run it on ubuntu server headless 18.04 it crashes.


Traceback (most recent call last):
  File "mongoToDriveUpdater.py", line 147, in <module>
    print(API.get("10kK02ho-qWemN8FTMu6r2zaF7c0Eoi-8"))
  File "mongoToDriveUpdater.py", line 81, in get
    file_resource = self.service.files().get(fileId=file_id, fields='webContentLink').execute()
  File "/home/saffira/env/lib/python3.6/site-packages/googleapiclient/_helpers.py", line 130, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/home/saffira/env/lib/python3.6/site-packages/googleapiclient/http.py", line 851, in execute
    method=str(self.method), body=self.body, headers=self.headers)
  File "/home/saffira/env/lib/python3.6/site-packages/googleapiclient/http.py", line 165, in _retry_request
    resp, content = http.request(uri, method, *args, **kwargs)
  File "/home/saffira/env/lib/python3.6/site-packages/google_auth_httplib2.py", line 187, in request
    self._request, method, uri, request_headers)
  File "/home/saffira/env/lib/python3.6/site-packages/google/auth/credentials.py", line 125, in before_request
    self.apply(headers)
  File "/home/saffira/env/lib/python3.6/site-packages/google/oauth2/credentials.py", line 185, in apply
    if self.quota_project_id is not None:
  File "/home/saffira/env/lib/python3.6/site-packages/google/oauth2/credentials.py", line 134, in quota_project_id
    return self._quota_project_id
AttributeError: 'Credentials' object has no attribute '_quota_project_id'

at this example I made a class that have a method get for testing, it gets the file specified by ID.

def get(self, file_id):
        file_resource = self.service.files().get(fileId=file_id, fields='webContentLink').execute()
        return file_resource

as you can see its a normal service.files().get() function call, but I dont know why the request crashes only using ubuntu server headless 18.04.

Im using
Python 3.6.9
here my venv "pip3 list", output:


cachetools (3.1.1)
certifi (2019.11.28)
chardet (3.0.4)
google-api-python-client (1.7.11)
google-auth (1.8.1)
google-auth-httplib2 (0.0.3)
google-auth-oauthlib (0.4.1)
httplib2 (0.14.0)
idna (2.8)
oauthlib (3.1.0)
pip (9.0.1)
pkg-resources (0.0.0)
pyasn1 (0.4.8)
pyasn1-modules (0.2.7)
pymongo (3.10.0)
requests (2.22.0)
requests-oauthlib (1.3.0)
rsa (4.0)
setuptools (42.0.2)
six (1.13.0)
uritemplate (3.0.0)
urllib3 (1.25.7)
wheel (0.33.6)

Can someone help me solve this issue?

Trailing slash preventing authorization

While authorizing I get this error:

400. That’s an error.

Error: redirect_uri_mismatch

The redirect URI in the request, http://localhost:8080/, does not match the ones authorized for the OAuth client. To update the authorized redirect URIs, visit: 
<redacted>

However, when I go there, it doesn't let me add a trailing slash on to the redirect URI.
Can anyone help?
Thanks in advance

release 0.4.2 undocumentedly breaks python <3.6 compatibility

Release 0.4.2 of this package breaks compatibility with all Python versions before 3.6. That is obviously something that is within your prerogative to do. However:

  • it should be documented in CHANGELOG.md
  • it should be documented in README.rst
  • it should not happen in a patch release
  • it should not happen in a commit whose message is "fix: don't open browser if port is occupied"

Url mismatch

Thanks for stopping by to let us know something could be better!

PLEASE READ: If you have a support contract with Google, please create an issue in the support console instead of filing on GitHub. This will ensure a timely response.

Please run down the following list and make sure you've tried the usual "quick fixes":

If you are still having issues, please be sure to include as much information as possible:

Error

Environment details

  • OS type and version: Ubuntu 18.10
  • Python version: Python 3.8.6
  • pip version: pip 9.0.2 from python 3.8
  • google-api-python-client version: 1.12.3

Steps to reproduce

  1. Copy the code from People API example
  2. Use the code below to get credentials
  3. Deploy your app to Heroku
  4. Login into Google Console. Register you app. Setup redirect url so that it matches the url of your Heroku application. I added it with https://.... Beside this, I also added http://localhost. Both url were withouth trailing slashes and withouth port numbers
  5. Run the app. It will produce the error

Code example

def get_creds(SCOPES):
    creds = None
    cred_dir = os.path.join(BASE_DIR, 'credentials.json')
    pickle_dir = os.path.join(BASE_DIR, 'token.pickle')

    # The file token.pickle is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists(pickle_dir):
        with open(pickle_dir, 'rb') as token:
            creds = pickle.load(token)

    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            config = json.loads(os.environ['CRED'])
            flow = InstalledAppFlow.from_client_config(config, SCOPES)
            flow.redirect_uri = os.environ['REDIRECT_URL']
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open(pickle_dir, 'wb') as token:
            pickle.dump(creds, token)
    return creds

Use it like this:

    creds = get_creds(['https://www.googleapis.com/auth/contacts'])

    service = build('people', 'v1', credentials=creds)

REDIRECT_URL is set to Heroku application url, starting with https://, withouth trailing slash. I also tested it in Python console:

>>> import os
>>> os.environ['REDIRECT_URL']

Stack trace

Browser output (there is no console stack trace):

400: redirect_uri_mismatch
The redirect URI in the request, http://localhost:33779/, does not match the ones authorized for the OAuth client. To update the authorized redirect URIs, visit: https://console.developers.google.com/apis/credentials/oauthclient/${your_client_id}?project=${your_project_number}

I think that the line:

flow.redirect_uri = os.environ['REDIRECT_URL']

does not actually change

Making sure to follow these steps will guarantee the quickest resolution possible.

Thanks!

Refresh Token is null after authenticating user account

Hi, I am trying to restrict the download and upload of files in google storage by using user authentication. I am using below code to authenticate the user account and getting the account details to connect with the cloud. But while getting the details from the account , refresh token is coming null. Do I need to configure anything to get refresh token.

    appflow = flow.InstalledAppFlow.from_client_secrets_file(client_secrets_file, 
    scopes='https://www.googleapis.com/auth/cloud-platform'])
    listen_port = 8080
    creds = appflow.run_local_server(
                port=listen_port,
                authorization_prompt_message=prompt,
                success_message=success)
    data = {           
        'refresh_token': creds.refresh_token,
        'token_uri': creds.token_uri,
        'client_id': creds.client_id,
        'client_secret': creds.client_secret,
        'scopes': creds.scopes
    }
    store_credentials(data, creds_file)

Install google_auth_oauthlib Python 3 on Mac

Hi,
I have tried to install google_auth_oauthlib into Python 3 with using pip and repository options.

  1. I get this error message for repository option:
    Execute comment: pip install --index-url https://github.com/googleapis/google-auth-library-python-oauthlib/ google_auth_oauthlib
    Error Occurred: ERROR: Could not find a version that satisfies the requirement google_auth_oauthlib (from versions: none)
    Command output: Looking in indexes: https://github.com/googleapis/google-auth-library-python-oauthlib/

ERROR: Could not find a version that satisfies the requirement google_auth_oauthlib (from versions: none)
ERROR: No matching distribution found for google_auth_oauthlib

  1. I didn't get error message for pip instal. But I couldn't see it in Python script when I use import command.
    Terminal output:
    Eness-MacBook-Pro:~ ea$ pip install google_auth_oauthlib
    Requirement already satisfied: google_auth_oauthlib in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (0.4.1)
    Requirement already satisfied: requests-oauthlib>=0.7.0 in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from google_auth_oauthlib) (1.3.0)
    Requirement already satisfied: google-auth in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from google_auth_oauthlib) (1.9.0)
    Requirement already satisfied: oauthlib>=3.0.0 in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from requests-oauthlib>=0.7.0->google_auth_oauthlib) (3.1.0)
    Requirement already satisfied: requests>=2.0.0 in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from requests-oauthlib>=0.7.0->google_auth_oauthlib) (2.22.0)
    Requirement already satisfied: six>=1.9.0 in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from google-auth->google_auth_oauthlib) (1.13.0)
    Requirement already satisfied: pyasn1-modules>=0.2.1 in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from google-auth->google_auth_oauthlib) (0.2.7)
    Requirement already satisfied: cachetools<3.2,>=2.0.0 in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from google-auth->google_auth_oauthlib) (3.1.1)
    Requirement already satisfied: rsa<4.1,>=3.1.4 in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from google-auth->google_auth_oauthlib) (4.0)
    Requirement already satisfied: setuptools>=40.3.0 in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from google-auth->google_auth_oauthlib) (42.0.2)
    Requirement already satisfied: certifi>=2017.4.17 in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from requests>=2.0.0->requests-oauthlib>=0.7.0->google_auth_oauthlib) (2019.11.28)
    Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from requests>=2.0.0->requests-oauthlib>=0.7.0->google_auth_oauthlib) (1.25.7)
    Requirement already satisfied: idna<2.9,>=2.5 in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from requests>=2.0.0->requests-oauthlib>=0.7.0->google_auth_oauthlib) (2.8)
    Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from requests>=2.0.0->requests-oauthlib>=0.7.0->google_auth_oauthlib) (3.0.4)
    Requirement already satisfied: pyasn1<0.5.0,>=0.4.6 in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from pyasn1-modules>=0.2.1->google-auth->google_auth_oauthlib) (0.4.8)

Question: how is authorization server able to send response to localhost?

Hi, this might be a naive question but it's been bugging me for a while. In this doc, it says that I can use localhost as the OAuth2.0 redirect_url, to which the server can send response. I'm wondering, when the authorization server sees that redirect URI as "http://localhost", how does it avoid sending the response to its own localhost (the computer hosting the server)?

My guess is that it automatically translate "localhost" into the incoming IP address where the request originated. Is this correct?

port=0 documentation for run_local_server()

Make clear in documentation that run_local_server(port=0) will automatically find a local port number not in use (and thus not in potential conflict). And consider making port=0 the default instead of 8080.

redirect_uri issue

self.redirect_uri = 'http://{}:{}/'.format(

Hello Team,

http://{}:{}/ <-- the extra slash is causing an issue, as project settings pages do not allow path to get configured for the redirect_uri; and python code is even ignoring the redirect_uri passed as an argument in InstalledAppFlow.from_client_secrets_file

I could use the library by removing extra slash. I wish this gets corrected as part of the library itself.

Thanks,
-Vikas.

Expecting property name enclosed in double quotes

I'm writing an app for a client that needs to write data to his Google Drive. I'm following the Python tutorial here. However, I'm getting an error.

flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
    "client_id.json",
    scopes=["https://www.googleapis.com/auth/drive.file"]
)
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f780bd04378>
web_1  | Traceback (most recent call last):
web_1  |   File "/virtualenv/lib/python3.5/site-packages/django/utils/autoreload.py", line 228, in wrapper
web_1  |     fn(*args, **kwargs)
web_1  |   File "/virtualenv/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 124, in inner_run
web_1  |     self.check(display_num_errors=True)
web_1  |   File "/virtualenv/lib/python3.5/site-packages/django/core/management/base.py", line 359, in check
web_1  |     include_deployment_checks=include_deployment_checks,
web_1  |   File "/virtualenv/lib/python3.5/site-packages/django/core/management/base.py", line 346, in _run_checks
web_1  |     return checks.run_checks(**kwargs)
web_1  |   File "/virtualenv/lib/python3.5/site-packages/django/core/checks/registry.py", line 81, in run_checks
web_1  |     new_errors = check(app_configs=app_configs)
web_1  |   File "/virtualenv/lib/python3.5/site-packages/django/core/checks/urls.py", line 16, in check_url_config
web_1  |     return check_resolver(resolver)
web_1  |   File "/virtualenv/lib/python3.5/site-packages/django/core/checks/urls.py", line 26, in check_resolver
web_1  |     return check_method()
web_1  |   File "/virtualenv/lib/python3.5/site-packages/django/urls/resolvers.py", line 256, in check
web_1  |     for pattern in self.url_patterns:
web_1  |   File "/virtualenv/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__
web_1  |     res = instance.__dict__[self.name] = self.func(instance)
web_1  |   File "/virtualenv/lib/python3.5/site-packages/django/urls/resolvers.py", line 407, in url_patterns
web_1  |     patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
web_1  |   File "/virtualenv/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__
web_1  |     res = instance.__dict__[self.name] = self.func(instance)
web_1  |   File "/virtualenv/lib/python3.5/site-packages/django/urls/resolvers.py", line 400, in urlconf_module
web_1  |     return import_module(self.urlconf_name)
web_1  |   File "/virtualenv/lib/python3.5/importlib/__init__.py", line 126, in import_module
web_1  |     return _bootstrap._gcd_import(name[level:], package, level)
web_1  |   File "<frozen importlib._bootstrap>", line 986, in _gcd_import
web_1  |   File "<frozen importlib._bootstrap>", line 969, in _find_and_load
web_1  |   File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
web_1  |   File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
web_1  |   File "<frozen importlib._bootstrap_external>", line 665, in exec_module
web_1  |   File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
web_1  |   File "/app/urls.py", line 11, in <module>
web_1  |     ] + aldryn_addons.urls.patterns() + i18n_patterns(
web_1  |   File "/virtualenv/lib/python3.5/site-packages/django/conf/urls/__init__.py", line 50, in include
web_1  |     urlconf_module = import_module(urlconf_module)
web_1  |   File "/virtualenv/lib/python3.5/importlib/__init__.py", line 126, in import_module
web_1  |     return _bootstrap._gcd_import(name[level:], package, level)
web_1  |   File "<frozen importlib._bootstrap>", line 986, in _gcd_import
web_1  |   File "<frozen importlib._bootstrap>", line 969, in _find_and_load
web_1  |   File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
web_1  |   File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
web_1  |   File "<frozen importlib._bootstrap_external>", line 665, in exec_module
web_1  |   File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
web_1  |   File "/app/authenticate/urls.py", line 3, in <module>
web_1  |     from . import views
web_1  |   File "/app/authenticate/views.py", line 106, in <module>
web_1  |     scopes=["https://www.googleapis.com/auth/drive.metadata.readonly"]
web_1  |   File "/virtualenv/lib/python3.5/site-packages/google_auth_oauthlib/flow.py", line 172, in from_client_secrets_file
web_1  |     client_config = json.load(json_file)
web_1  |   File "/usr/local/lib/python3.5/json/__init__.py", line 268, in load
web_1  |     parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
web_1  |   File "/usr/local/lib/python3.5/json/__init__.py", line 319, in loads
web_1  |     return _default_decoder.decode(s)
web_1  |   File "/usr/local/lib/python3.5/json/decoder.py", line 339, in decode
web_1  |     obj, end = self.raw_decode(s, idx=_w(s, 0).end())
web_1  |   File "/usr/local/lib/python3.5/json/decoder.py", line 355, in raw_decode
web_1  |     obj, end = self.scan_once(s, idx)
web_1  | json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 12 column 3 (char 534)

Trailing Slash Breaks redirect_uri for localhost

The concatenation of a slash on the end of the redirect_uri means that the redirect no longer matches what the server side expects for redirect_uri.

Example:
redirect_uris= ['http://localhost:8080']
from client_config.json downloaded from https://console.cloud.google.com/apis/credentials

After flow adds the slash.
The oauth url opened in the browser has:
"...&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2F&..."
the extra slash.
If I remove the %2F slash from the URL it works.

I guess this may be more a problem on the server side as it should probably still accept the URL with the slash.
Over on https://console.cloud.google.com/apis/credentials it doesn't allow adding a trailing slash anyway.
It's on line 456 of flow.py.

Error page from the extra slash URL:
"
Fehler bei der Autorisierung
Fehler 400: redirect_uri_mismatch
The redirect URI in the request, http://localhost:8080/, does not match the ones authorized for the OAuth client. To update the authorized redirect URIs, visit: https://console.developers.google.com/apis/credentials/oauthclient/53469...
"

Add optional expiration parameter to google.oauth2.credentials.Credentials

I store the credentials object in the session, and the expiration as well, since I need to call credentials.valid to check the creds validity on session setup.

Currently I have to do this:

creds = session['creds']
expiry = creds.pop('expiry')
creds = google.oauth2.credentials.Credentials(**creds)
creds.expiry = datetime.utcfromtimestamp(expiry)
if not creds.valid:
      return False

Would be nice to add exiry to Credentials constructor that defaults to None so as not to break backward compatibillity

Credential object stopped to receive refresh_token

Hi, I've noticed last week that

credentials = flow.credentials

has stopped to receive refresh_token, so it's None
google-auth-oauthlib==0.2.0

I've updated also to 0.4.1 but still no luck, refresh_token is empty

Feature Request: `get_user_credentials` method that runs the installed application flow

There are times in development and the data scientist workflow, where it is useful to have explicit user-based credentials. I happen to like the way I did this in the pydata-google-auth library and would like to contribute it here, if you're open to it.

pydata-google-auth

pydata_google_auth.get_user_credentials(
    scopes,
    client_id=None,
    client_secret=None,
    credentials_cache=<pydata_google_auth.cache.ReadWriteCredentialsCache object>,
    use_local_webserver=False)

google-auth-oauthlib

google_auth_oauthlib.get_user_credentials(
    scopes, client_id=None, client_secret=None, use_local_webserver=False)

Differences:

  • I propose is that this library doesn't need to handle any cache mechanism. As I understand it, caching credentials is out-of-scope for this library.
  • client_id and client_secret are still optional. Ideally, this would not require the developer / data scientist to download a client secret, as the ADC client secret could be used.

run_local_server blocks if port is unavailable

Executing

flow.run_local_server(host='localhost',
    port=8888, 
    authorization_prompt_message='Please visit this URL: {url}', 
    success_message='The auth flow is complete; you may close this window.',
    open_browser=True)

with something listening on port 8888 already blocks the process, rather then returning an error message.

Would be partially mitigated by #23 being merged, but this situation should throw an exception.

Can't run flow.run_local_server from a Docker container

I am making a Flask API that I try to containerize.

I am using the google_auth_oauthlib module to get the authorization from the user of my application to use his YouTube account.

This is performed in the _get_authenticated_first_time function of this python file.
It works fine on my local server.

However, when I am tying to containerize my application with Docker, the function flow.run_local_server runs forever without redirecting me anywhere.

I tried to pass as port argument of the flow.run_local_server() the value 8080 and map my local port 8080 to the port 8080 of the container in my docker-compose.yaml file but it doesn't work either.

So my question is simple:
Do you know how to make a set up that allows to run the authentication flow inside a Docker container?

make redirect host configurable

I am using docker for windows which runs the docker daemon inside a Hyper-V VM.
This library is used inside a docker container and for authentication purposes the corresponding port is exposed to my machine. This way I can access the launched WSGI server on localhost on my machine, however the server inside the docker container does only listen on the ip behind localhost resolved within the container -> You do not receive an answer for localhost on your machine, only within the container (e.g. with curl)
This could easily be mitigated by passing an empty String as host parameter to the Flow.run_local_server function, but this will raise an error because the redirect url is equal to the chosen host string -> empty URL is not possible

As a solution the function could be extended by an optional parameter redirect_host that defaults to the value of host and is inserted into the redirect_host variable.

Using default credentials with a flow

Hi,

I want to be able to use the default credentials in my app engine environment to initiate a login flow.

Currently I use flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(self.key_path, scopes=['https://www.googleapis.com/auth/spreadsheets'])

But I don't want to have to include a service_account.json with my application.

Is it possible to use google.auth.default() credentials with a flow?

Thanks

How do I get the access token from a code I already have?

I used ReactGoogleLogin (https://github.com/anthonyjgrove/react-google-login) to get the offline code. This works fine and is associated with my clientId. I then want to have the server complete the process with this API.

Doing the following does not work and yields an error oauthlib.oauth2.rfc6749.errors.InvalidGrantError: (invalid_grant) code_verifier or verifier is not needed.. How do I fix this?

def fetch_token(code):
  flow = Flow.from_client_secrets_file(</path/to/credentials.json>, [list of scopes], 
    redirect_uri='urn:ietf:wg:oauth:2.0:oob')
  flow.fetch_token(code)

Note that I tried this w/ and w/o the redirect_uri. I also tried it with the redirect_uri for my website. All gave the same error.

Link to docs from README

Not seeing where the docs are located (if they are published at all). We should link to them from the README file.

it is better to keep expiry data from oauth2session

the helper function credentials_from_session helps to generate Credentials object from session. But, it does not carry expires_at data from oauth2session.token

It is better that the expiry can be carried to Credentials object. So, caller can check expired property of Credentials to know whether the token expired.

Thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.