requests-oauthlib

repository·master·Indexed 23 days ago

https://github.com/requests/requests-oauthlib

Provides first-class OAuth support for the Requests library, simplifying the implementation of OAuth 1 and OAuth 2 workflows. It includes the OAuth1 and OAuth2 classes for individual requests, as well as OAuth1Session and OAuth2Session for persisting authentication state. The library provides tools for handling token refreshes via TokenUpdated, parsing tokens from URL fragments with token_from_fragment(), and includes compliance fixes for specific providers like Facebook.

Tokens
16.5K
Snippets
31
Records
41
Agent score
81%

What's inside requests-oauthlib

  1. Overview of OAuth 2 workflows

    master
    Requests-OAuthlib supports OAuth 2 workflows, such as the Authorization Code Grant (WebApplication flow). While the library simplifies fetching protected resources once an access token is obtained, the initial process of obtaining credentials and user authorization depends on the specific provider (e.g., Google).
  2. Implement the OAuth 1 workflow using the OAuth1 auth helper

    master

    The OAuth1 class is an authentication helper that can be passed to the auth parameter of standard requests methods. This is useful if you prefer to manage the session and token state manually.

    Workflow Steps:

    1. Initialize: Create an OAuth1 instance with client_key and client_secret.
    2. Request Token: Use requests.post(url, auth=oauth) to get the request token and secret from the response body.
    3. Authorize: Manually construct the authorization URL by appending the oauth_token as a query parameter. The user provides a verifier manually.
    4. Access Token: Create a new OAuth1 instance including the resource_owner_key, resource_owner_secret, and verifier, then use requests.post(url, auth=oauth) to fetch the access token.
    5. Access Resources: Create a final OAuth1 instance with the access tokens and pass it to requests.get(url, auth=oauth).
    import requests
    from requests_oauthlib import OAuth1
    
    # 1. Initialize
    oauth = OAuth1(client_key, client_secret=client_secret)
    
    # 2. Obtain request token
    r = requests.post(url=request_token_url, auth=oauth)
    # Parse r.content (e.g., using parse_qs) to get resource_owner_key and resource_owner_secret
    
    # 3. Obtain authorization
    authorize_url = base_authorization_url + '?oauth_token=' + resource_owner_key
    # ... user provides verifier ...
    verifier = input('Please input the verifier')
    
    # 4. Obtain access token
    oauth = OAuth1(client_key,
                   client_secret=client_secret,
                   resource_owner_key=resource_owner_key,
                   resource_owner_secret=resource_owner_secret,
                   verifier=verifier)
    r = requests.post(url=access_token_url, auth=oauth)
    # Parse r.content to get final resource_owner_key and resource_owner_secret
    
    # 5. Access protected resources
    oauth = OAuth1(client_key,
                   client_secret=client_secret,
                   resource_owner_key=resource_owner_key,
                   resource_owner_secret=resource_owner_secret)
    r = requests.get(url=protected_url, auth=oauth)
  3. Implement Fitbit OAuth 2 (Mobile Application Flow) using Implicit Grant

    master

    To use the Fitbit API with the Mobile Application Flow (Implicit Grant Flow), you must use MobileApplicationClient from oauthlib.oauth2 passed into a requests_oauthlib.OAuth2Session.

    Workflow Steps:

    1. Initialize: Create a MobileApplicationClient with your client_id and initialize an OAuth2Session with the client, your client_id, and the required scope.
    2. Authorize: Generate the authorization URL using fitbit.authorization_url(authorization_url). The user must visit this URL in a browser to authenticate.
    3. Capture Callback: After authentication, Fitbit redirects to your callback URL containing the access token in the URL fragment.
    4. Extract Token: Use fitbit.token_from_fragment(callback_url) to parse the token from the redirect URL.
    5. Make Requests: Once the token is extracted, use the OAuth2Session instance to make authenticated requests to the Fitbit API.
    import requests
    from requests_oauthlib import OAuth2Session
    from oauthlib.oauth2 import MobileApplicationClient
    
    # 1. Setup
    client_id = "<your client ID here>"
    scope = ["activity", "heartrate", "location", "nutrition", "profile", "settings", "sleep", "social", "weight"]
    
    # 2. Initialize client
    client = MobileApplicationClient(client_id)
    fitbit = OAuth2Session(client_id, client=client, scope=scope)
    authorization_url = "https://www.fitbit.com/oauth2/authorize"
    
    # 3. Get Authorization URL
    auth_url, state = fitbit.authorization_url(authorization_url)
    print("Visit this page in your browser: {}".format(auth_url))
    
    # 4. Handle Callback (User pastes the URL they were redirected to)
    callback_url = input("Paste URL you get back here: ")
    
    # 5. Extract token from fragment
    fitbit.token_from_fragment(callback_url)
    
    # 6. Make API calls
    r = fitbit.get('https://api.fitbit.com/1/user/-/sleep/goal.json')
  4. Implement Mobile Application Flow (Implicit Grant)

    master

    Use the Implicit Grant flow for mobile or client-side applications where the access token is returned directly in the URL fragment after authorization.

    1. Initialize OAuth2Session using a MobileApplicationClient from oauthlib.oauth2.
    2. Get the authorization_url.
    3. After the user redirects, use oauth.token_from_fragment(response.url) to extract the token from the URL fragment.
    from oauthlib.oauth2 import MobileApplicationClient
    from requests_oauthlib import OAuth2Session
    
    client_id = 'your_client_id'
    scopes = ['scope_1', 'scope_2']
    auth_url = 'https://your.oauth2/auth'
    
    # 1. Get the authorization_url
    oauth = OAuth2Session(client=MobileApplicationClient(client_id=client_id), scope=scopes)
    authorization_url, state = oauth.authorization_url(auth_url)
    
    # 2. Fetch an access token from the provider
    response = oauth.get(authorization_url)
    oauth.token_from_fragment(response.url)
  5. Implement Backend Application Flow (Client Credentials Grant)

    master

    Use the Client Credentials Grant flow for machine-to-machine (backend) communication where no user is involved.

    Option 1: Standard Request Initialize OAuth2Session with a BackendApplicationClient and call fetch_token() with client_id and client_secret.

    Option 2: Basic Auth Header If your provider requires credentials in a Basic Auth header, pass a requests.auth.HTTPBasicAuth object to the auth parameter of fetch_token().

    # Option 1: Standard
    from oauthlib.oauth2 import BackendApplicationClient
    from requests_oauthlib import OAuth2Session
    
    client_id = 'your_client_id'
    client_secret = 'your_client_secret'
    
    client = BackendApplicationClient(client_id=client_id)
    oauth = OAuth2Session(client=client)
    token = oauth.fetch_token(token_url='https://provider.com/oauth2/token', client_id=client_id, client_secret=client_secret)
    
    # Option 2: Using Basic Auth
    from oauthlib.oauth2 import BackendApplicationClient
    from requests_oauthlib import OAuth2Session
    from requests.auth import HTTPBasicAuth
    
    auth = HTTPBasicAuth(client_id, client_secret)
    client = BackendApplicationClient(client_id=client_id)
    oauth = OAuth2Session(client=client)
    token = oauth.fetch_token(token_url='https://provider.com/oauth2/token', auth=auth)
  6. Implement Legacy Application Flow (Resource Owner Password Credentials)

    master

    Use the Resource Owner Password Credentials Grant flow when you have direct access to the user's username and password. This is considered a legacy flow.

    1. Initialize OAuth2Session using a LegacyApplicationClient from oauthlib.oauth2.
    2. Call oauth.fetch_token() providing the token_url, username, password, client_id, and optionally client_secret.
    from oauthlib.oauth2 import LegacyApplicationClient
    from requests_oauthlib import OAuth2Session
    
    client_id = 'your_client_id'
    client_secret = 'your_client_secret'
    username = 'your_username'
    password = 'your_password'
    
    # 1. Fetch an access token
    oauth = OAuth2Session(client=LegacyApplicationClient(client_id=client_id))
    token = oauth.fetch_token(
        token_url='https://somesite.com/oauth2/token',
        username=username, 
        password=password, 
        client_id=client_id,
        client_secret=client_secret
    )
  7. Implement the OAuth 1 workflow using OAuth1Session

    master

    The OAuth1Session class provides a high-level, convenient way to complete the OAuth 1 workflow. It manages the state of the authentication process across multiple steps.

    Workflow Steps:

    1. Initialize: Create an OAuth1Session with your client_key and client_secret.
    2. Request Token: Call .fetch_request_token(url) to obtain a request token and secret.
    3. Authorize: Use .authorization_url(base_url) to generate the URL for user authorization. After the user redirects back, use .parse_authorization_response(redirect_url) to extract the oauth_verifier.
    4. Access Token: Call .fetch_access_token(url) using the previously obtained credentials and the verifier to get the final oauth_token and oauth_token_secret.
    5. Access Resources: Create a new OAuth1Session instance with the final access tokens to make authenticated requests.
    from requests_oauthlib import OAuth1Session
    
    # 1. Initialize
    oauth = OAuth1Session(client_key, client_secret=client_secret)
    
    # 2. Obtain request token
    fetch_response = oauth.fetch_request_token(request_token_url)
    resource_owner_key = fetch_response.get('oauth_token')
    resource_owner_secret = fetch_response.get('oauth_token_secret')
    
    # 3. Obtain authorization
    authorization_url = oauth.authorization_url(base_authorization_url)
    # ... user visits URL and redirects back ...
    oauth_response = oauth.parse_authorization_response(redirect_response)
    verifier = oauth_response.get('oauth_verifier')
    
    # 4. Obtain access token
    oauth = OAuth1Session(client_key,
                              client_secret=client_secret,
                              resource_owner_key=resource_owner_key,
                              resource_owner_secret=resource_owner_secret,
                              verifier=verifier)
    oauth_tokens = oauth.fetch_access_token(access_token_url)
    resource_owner_key = oauth_tokens.get('oauth_token')
    resource_owner_secret = oauth_tokens.get('oauth_token_secret')
    
    # 5. Access protected resources
    oauth = OAuth1Session(client_key,
                              client_secret=client_secret,
                              resource_owner_key=resource_owner_key,
                              resource_owner_secret=resource_owner_secret)
    r = oauth.get(protected_url)
  8. Complete OAuth 2 workflow with token refresh

    master

    A standard OAuth 2 flow involves three main steps:

    1. User Authorization: Redirect the user to the provider's authorization_base_url using OAuth2Session.authorization_url(). To receive a refresh token, ensure you pass provider-specific parameters like access_type='offline' (for Google).
    2. Token Retrieval: After the user authorizes, the provider redirects to your redirect_uri with an authorization code. Use OAuth2Session.fetch_token() to exchange this code for an access token.
    3. Resource Access: Use the OAuth2Session with the obtained token to make authenticated requests to protected resources.
    # 1. Authorization URL
    google = OAuth2Session(client_id, scope=scope, redirect_uri=redirect_uri)
    authorization_url, state = google.authorization_url(
        authorization_base_url, 
        access_type="offline", 
        prompt="select_account"
    )
    
    # 2. Fetch Token
    google = OAuth2Session(client_id, redirect_uri=redirect_uri, state=state)
    token = google.fetch_token(
        token_url, 
        client_secret=client_secret, 
        authorization_response=request.url
    )
    
    # 3. Access Resource
    google = OAuth2Session(client_id, token=token)
    response = google.get('https://www.googleapis.com/oauth2/v1/userinfo')
  9. Implement the Google OAuth 2 workflow

    master

    The Google OAuth 2 workflow using requests-oauthlib involves four main steps:

    1. Initialize the Session: Create an OAuth2Session instance using your client_id, scope, and redirect_uri.
    2. Authorize the User: Generate an authorization URL using google.authorization_url(). You can pass access_type="offline" to request a refresh token and prompt="select_account" to force the user to choose an account.
    3. Fetch the Token: After the user authorizes, capture the full redirect URL and use google.fetch_token() with the token_url and your client_secret to exchange the authorization code for an access token.
    4. Access Protected Resources: Use the authenticated google session to make requests (e.g., .get()) to Google API endpoints.
    from requests_oauthlib import OAuth2Session
    
    # 1. Setup credentials and endpoints
    client_id = '<the id you get from google>'
    client_secret = '<the secret you get from google>'
    redirect_uri = 'https://your.registered/callback'
    authorization_base_url = "https://accounts.google.com/o/oauth2/v2/auth"
    token_url = "https://www.googleapis.com/oauth2/v4/token"
    scope = [
        "openid",
        "https://www.googleapis.com/auth/userinfo.email",
        "https://www.googleapis.com/auth/userinfo.profile"
    ]
    
    # 2. Initialize session
    google = OAuth2Session(client_id, scope=scope, redirect_uri=redirect_uri)
    
    # 3. Redirect user to Google for authorization
    authorization_url, state = google.authorization_url(
        authorization_base_url, 
        access_type="offline", 
        prompt="select_account"
    )
    print('Please go here and authorize:', authorization_url)
    
    # 4. Get the authorization verifier code from the callback url
    redirect_response = input('Paste the full redirect URL here: ')
    
    # 5. Fetch the access token
    google.fetch_token(token_url, client_secret=client_secret, authorization_response=redirect_response)
    
    # 6. Fetch a protected resource
    r = google.get('https://www.googleapis.com/oauth2/v1/userinfo')
    print(r.content)