OAuth 2.0 Client Library

4.1.3 · deprecated · verified Sun Mar 29

oauth2client is a Python library designed for interacting with OAuth 2.0 protected resources, primarily for Google APIs. As of version 4.1.0, the library is officially deprecated, with no new features planned and limited support. Users are strongly advised to migrate to `google-auth` and `oauthlib` for modern and actively maintained OAuth 2.0 client functionality. The current version is 4.1.3.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates a basic OAuth 2.0 web server flow using `oauth2client.client.OAuth2WebServerFlow` and `oauth2client.tools.run_flow` to obtain user credentials. The `run_flow` utility is suitable for local development as it opens a browser for user interaction. In a production web application, the authorization redirect and code exchange steps would be handled explicitly. Credentials are saved to a local JSON file using `oauth2client.file.Storage` for simplicity.

import os
import httplib2 # oauth2client relies heavily on httplib2
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.tools import run_flow
from oauth2client.file import Storage

# NOTE: This library is deprecated. Consider migrating to google-auth and oauthlib.

# These values would typically come from your Google API Console project.
# For a quickstart, we use environment variables for demonstration.
CLIENT_ID = os.environ.get('OAUTH2CLIENT_CLIENT_ID', 'YOUR_CLIENT_ID')
CLIENT_SECRET = os.environ.get('OAUTH2CLIENT_CLIENT_SECRET', 'YOUR_CLIENT_SECRET')
REDIRECT_URI = 'http://localhost:8080/oauth2callback' # Must match a registered redirect URI in your Google project

def main():
    if CLIENT_ID == 'YOUR_CLIENT_ID' or CLIENT_SECRET == 'YOUR_CLIENT_SECRET':
        print("Please set OAUTH2CLIENT_CLIENT_ID and OAUTH2CLIENT_CLIENT_SECRET environment variables,")
        print("or replace 'YOUR_CLIENT_ID' and 'YOUR_CLIENT_SECRET' in the code.")
        return

    # 1. Create a flow object for a web server application
    flow = OAuth2WebServerFlow(
        client_id=CLIENT_ID,
        client_secret=CLIENT_SECRET,
        scope='https://www.googleapis.com/auth/userinfo.email',
        redirect_uri=REDIRECT_URI
    )

    # 2. Authorize the user
    # The `run_flow` function is typically used for local development and
    # will open a browser window for user authentication.
    # In a production web application, you would manage the redirects and
    # authorization code exchange manually.
    try:
        http = httplib2.Http()
        # Simple file storage for credentials; in production, use a secure database.
        storage = Storage('oauth2client_creds.json')
        
        print(f"Attempting to authorize. Please check your browser or navigate to: {flow.step1_get_authorize_url()}")
        credentials = run_flow(flow, storage, http=http)

        print(f"\nAuthorization successful!")
        print(f"Access Token: {credentials.access_token[:10]}...{credentials.access_token[-10:]}")
        if credentials.refresh_token:
            print(f"Refresh Token: {credentials.refresh_token[:10]}...{credentials.refresh_token[-10:]}")
        else:
            print("No Refresh Token (may be due to scope or one-time access).")
        print(f"Credentials saved to: {storage.filename}")
        
    except Exception as e:
        print(f"\nAn error occurred during OAuth2 flow: {e}")
        print("Ensure your client ID, client secret, and redirect URI are correctly configured and match your Google project.")
        print("Also, ensure 'oauth2client_creds.json' is writable or doesn't exist.")
        
if __name__ == '__main__':
    main()

view raw JSON →