requests-oauthlib
repository·master·Indexed 23 days ago
https://github.com/requests/requests-oauthlibProvides 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.
What's inside requests-oauthlib
- 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).
Implement the OAuth 1 workflow using the OAuth1 auth helper
masterThe
OAuth1class is an authentication helper that can be passed to theauthparameter of standardrequestsmethods. This is useful if you prefer to manage the session and token state manually.Workflow Steps:
- Initialize: Create an
OAuth1instance withclient_keyandclient_secret. - Request Token: Use
requests.post(url, auth=oauth)to get the request token and secret from the response body. - Authorize: Manually construct the authorization URL by appending the
oauth_tokenas a query parameter. The user provides a verifier manually. - Access Token: Create a new
OAuth1instance including theresource_owner_key,resource_owner_secret, andverifier, then userequests.post(url, auth=oauth)to fetch the access token. - Access Resources: Create a final
OAuth1instance with the access tokens and pass it torequests.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)- Initialize: Create an
Implement Fitbit OAuth 2 (Mobile Application Flow) using Implicit Grant
masterTo use the Fitbit API with the Mobile Application Flow (Implicit Grant Flow), you must use
MobileApplicationClientfromoauthlib.oauth2passed into arequests_oauthlib.OAuth2Session.Workflow Steps:
- Initialize: Create a
MobileApplicationClientwith yourclient_idand initialize anOAuth2Sessionwith the client, yourclient_id, and the requiredscope. - Authorize: Generate the authorization URL using
fitbit.authorization_url(authorization_url). The user must visit this URL in a browser to authenticate. - Capture Callback: After authentication, Fitbit redirects to your callback URL containing the access token in the URL fragment.
- Extract Token: Use
fitbit.token_from_fragment(callback_url)to parse the token from the redirect URL. - Make Requests: Once the token is extracted, use the
OAuth2Sessioninstance 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')- Initialize: Create a
Implement Mobile Application Flow (Implicit Grant)
masterUse the Implicit Grant flow for mobile or client-side applications where the access token is returned directly in the URL fragment after authorization.
- Initialize
OAuth2Sessionusing aMobileApplicationClientfromoauthlib.oauth2. - Get the
authorization_url. - 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)- Initialize
Implement Backend Application Flow (Client Credentials Grant)
masterUse the Client Credentials Grant flow for machine-to-machine (backend) communication where no user is involved.
Option 1: Standard Request Initialize
OAuth2Sessionwith aBackendApplicationClientand callfetch_token()withclient_idandclient_secret.Option 2: Basic Auth Header If your provider requires credentials in a Basic Auth header, pass a
requests.auth.HTTPBasicAuthobject to theauthparameter offetch_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)Implement Legacy Application Flow (Resource Owner Password Credentials)
masterUse the Resource Owner Password Credentials Grant flow when you have direct access to the user's
usernameandpassword. This is considered a legacy flow.- Initialize
OAuth2Sessionusing aLegacyApplicationClientfromoauthlib.oauth2. - Call
oauth.fetch_token()providing thetoken_url,username,password,client_id, and optionallyclient_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 )- Initialize
Setup Google OAuth 2 credentials
masterTo use Google OAuth 2 withrequests-oauthlib, you must first create a web application project in the Google Cloud Console. From the console, you need to obtain yourclient_idandclient_secret, and register a validredirect_uri(callback URL).Implement the OAuth 1 workflow using OAuth1Session
masterThe
OAuth1Sessionclass 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:
- Initialize: Create an
OAuth1Sessionwith yourclient_keyandclient_secret. - Request Token: Call
.fetch_request_token(url)to obtain a request token and secret. - 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 theoauth_verifier. - Access Token: Call
.fetch_access_token(url)using the previously obtained credentials and the verifier to get the finaloauth_tokenandoauth_token_secret. - Access Resources: Create a new
OAuth1Sessioninstance 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)- Initialize: Create an
Set GitHub Action secrets via GitHub CLI
masterTo set new environment secrets required for testing (such as
AUTH0_PASSWORD) using the GitHub CLI, use thegh secret setcommand.gh secret set AUTH0_PASSWORD --body "secret"Install requests-oauthlib via pip
masterTo use this library, you need to install both
requestsandrequests-oauthlibusing pip.pip install requests requests-oauthlibComplete OAuth 2 workflow with token refresh
masterA standard OAuth 2 flow involves three main steps:
- User Authorization: Redirect the user to the provider's
authorization_base_urlusingOAuth2Session.authorization_url(). To receive a refresh token, ensure you pass provider-specific parameters likeaccess_type='offline'(for Google). - Token Retrieval: After the user authorizes, the provider redirects to your
redirect_uriwith an authorization code. UseOAuth2Session.fetch_token()to exchange this code for an access token. - Resource Access: Use the
OAuth2Sessionwith the obtainedtokento 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')- User Authorization: Redirect the user to the provider's
Implement the Google OAuth 2 workflow
masterThe Google OAuth 2 workflow using
requests-oauthlibinvolves four main steps:- Initialize the Session: Create an
OAuth2Sessioninstance using yourclient_id,scope, andredirect_uri. - Authorize the User: Generate an authorization URL using
google.authorization_url(). You can passaccess_type="offline"to request a refresh token andprompt="select_account"to force the user to choose an account. - Fetch the Token: After the user authorizes, capture the full redirect URL and use
google.fetch_token()with thetoken_urland yourclient_secretto exchange the authorization code for an access token. - Access Protected Resources: Use the authenticated
googlesession 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)- Initialize the Session: Create an