pythongoogle-apigoogle-oauthgoogle-api-python-clientoauth2client

How to implement google signin hybrid server-side flow without python oauth2client lib


I have implemented hybrid server side google signin flow using python27. Where webapp sends one time code to backend and backend replaces with refresh_token, id_token and access_token. I have followed this doc to implement this https://developers.google.com/identity/sign-in/web/server-side-flow

But looks like oauth2client is deprecated. And according to deprecated notes google-auth does not have any method to implement one time code auth flow.

Code below is handling one time auth_code and replaces with tokens. What is the best way to do this for both python 2.7 and 3.7 without oauth2client?

from apiclient import discovery
import httplib2
from oauth2client import client

CLIENT_SECRET_FILE = '/path/to/client_secret.json'

# Exchange auth code for access token, refresh token, and ID token
credentials = client.credentials_from_clientsecrets_and_code(
                   CLIENT_SECRET_FILE,
                   ['profile', 'email'],
                   auth_code)

Solution

  • If my understanding is correct, how about this modification? In this modification, I used google_auth_oauthlib. Please think of this as just one of several answers.

    Modified script:

    from google_auth_oauthlib.flow import Flow
    from googleapiclient.discovery import build
    
    # Create the flow using the client secrets file from the Google API Console.
    flow = Flow.from_client_secrets_file(
        'client_secret.json',
        scopes=['https://www.googleapis.com/auth/drive.metadata.readonly'],
        redirect_uri='urn:ietf:wg:oauth:2.0:oob')
    
    # Tell the user to go to the authorization URL.
    auth_url, _ = flow.authorization_url(prompt='consent')
    
    print('Please go to this URL: {}'.format(auth_url))
    
    # The user will get an authorization code. This code is used to get the access token.
    code = input('Enter the authorization code: ')
    flow.fetch_token(code=code)
    credentials = flow.credentials
    
    # Retrieve file list using Drive API. This is a sample.
    service = build('drive', 'v3', credentials=credentials)
    files = service.files().list(pageSize=5).execute()
    print(files)
    

    Reference:

    If I misunderstood your question and this was not the direction you want, I apologize.