### Flask Application Setup Source: https://github.com/requests/requests-oauthlib/blob/master/docs/examples/real_world_example_with_refresh.md Configures the Flask application, enabling insecure transport for OAuthlib and setting a secret key for session management. This is the main entry point for running the example. ```python if __name__ == "__main__": # This allows us to use a plain HTTP callback import os os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = "1" app.secret_key = os.urandom(24) app.run(debug=True) ``` -------------------------------- ### Install Requests and Requests-OAuthlib Source: https://github.com/requests/requests-oauthlib/blob/master/README.rst Install the necessary libraries using pip. This command installs both requests and requests_oauthlib. ```bash pip install requests requests-oauthlib ``` -------------------------------- ### Install Requests-OAuthlib Source: https://github.com/requests/requests-oauthlib/blob/master/docs/index.md Install the Requests-OAuthlib library using pip. This command fetches and installs the latest stable version of the package and its dependencies. ```bash $ pip install requests-oauthlib ``` -------------------------------- ### Install Python Versions with Pyenv Source: https://github.com/requests/requests-oauthlib/blob/master/docs/contributing.md Install specific Python versions using pyenv. This is recommended for testing across multiple Python environments. ```bash $ pyenv install 3.8.18 $ pyenv install pypy3.10-7.3.13 $ pyenv global pypy3.10-7.3.13 # switch to pypy ``` -------------------------------- ### GitHub OAuth 2 Authorization Flow Source: https://github.com/requests/requests-oauthlib/blob/master/docs/examples/github.md This example shows the complete flow for authenticating with GitHub using OAuth 2.0. It includes setting up the OAuth session, redirecting the user for authorization, and fetching the access token. ```python >>> # Credentials you get from registering a new application >>> client_id = '' >>> client_secret = '' >>> # OAuth endpoints given in the GitHub API documentation >>> authorization_base_url = 'https://github.com/login/oauth/authorize' >>> token_url = 'https://github.com/login/oauth/access_token' >>> from requests_oauthlib import OAuth2Session >>> github = OAuth2Session(client_id) >>> # Redirect user to GitHub for authorization >>> authorization_url, state = github.authorization_url(authorization_base_url) >>> print('Please go here and authorize,', authorization_url) >>> # Get the authorization verifier code from the callback url >>> redirect_response = input('Paste the full redirect URL here:') >>> # Fetch the access token >>> github.fetch_token(token_url, client_secret=client_secret, >>> authorization_response=redirect_response) >>> # Fetch a protected resource, i.e. user profile >>> r = github.get('https://api.github.com/user') >>> print(r.content) ``` -------------------------------- ### Python Example for PKCE Flow with Auth0 Source: https://github.com/requests/requests-oauthlib/blob/master/docs/examples/native_spa_pkce_auth0.md Use this Python script to initiate the OAuth2.0 Authorization Code with PKCE flow. It requires your Auth0 client ID, domain, and a registered callback URL. The script prints the authorization URL and prompts for the redirect response to fetch the token. ```python client_id = 'OAUTH_CLIENT_ID' authorization_base_url = "https://OAUTH_IDP_DOMAIN/authorize" token_url = "https://OAUTH_IDP_DOMAIN/oauth/token" scope = ["openid"] from requests_oauthlib import OAuth2Session redirect_uri = 'http://localhost:8080/callback' session = OAuth2Session(client_id, scope=scope, redirect_uri=redirect_uri, pkce="S256") authorization_url, state = session.authorization_url(authorization_base_url,access_type="offline") print("Please go here and authorize:") print(authorization_url) redirect_response = input('Paste the full redirect URL here: ') token = session.fetch_token(token_url, authorization_response=redirect_response, include_client_id=True) print(token) ``` -------------------------------- ### Flask OAuth2 Session with GitHub API Source: https://github.com/requests/requests-oauthlib/blob/master/docs/index.md This example demonstrates a basic Flask application integrating with the GitHub OAuth2 API. It shows how to initiate the OAuth flow, redirect the user for authorization, and fetch user data upon callback. Ensure you replace placeholders with your actual client ID, client secret, and Flask secret key. ```python from requests_oauthlib import OAuth2Session from flask import Flask, request, redirect, session from flask.json import jsonify # This information is obtained upon registration of a new GitHub client_id = "" client_secret = "" authorization_base_url = 'https://github.com/login/oauth/authorize' token_url = 'https://github.com/login/oauth/access_token' secret_key = "" app = Flask(__name__) app.config['SECRET_KEY'] = secret_key @app.route("/login") def login(): github = OAuth2Session(client_id) authorization_url, state = github.authorization_url(authorization_base_url) # State is used to prevent CSRF, keep this for later. session['oauth_state'] = state return redirect(authorization_url) @app.route("/callback") def callback(): github = OAuth2Session(client_id, state=session['oauth_state']) token = github.fetch_token(token_url, client_secret=client_secret, authorization_response=request.url) return jsonify(github.get('https://api.github.com/user').json()) ``` -------------------------------- ### Bitbucket OAuth 1 Flow with Python Source: https://github.com/requests/requests-oauthlib/blob/master/docs/examples/bitbucket.md This example shows the complete OAuth 1 flow for Bitbucket, including fetching request tokens, user authorization, and accessing protected resources. Ensure you have obtained your API key and secret from Bitbucket. ```python # Credentials you get from adding a new consumer in bitbucket -> manage account # -> integrated applications. >>> key = '' >>> secret = '' >>> # OAuth endpoints given in the Bitbucket API documentation >>> request_token_url = 'https://bitbucket.org/!api/1.0/oauth/request_token' >>> authorization_base_url = 'https://bitbucket.org/!api/1.0/oauth/authenticate' >>> access_token_url = 'https://bitbucket.org/!api/1.0/oauth/access_token' >>> # 2. Fetch a request token >>> from requests_oauthlib import OAuth1Session >>> bitbucket = OAuth1Session(key, client_secret=secret, >>> callback_uri='http://127.0.0.1/cb') >>> bitbucket.fetch_request_token(request_token_url) >>> # 3. Redirect user to Bitbucket for authorization >>> authorization_url = bitbucket.authorization_url(authorization_base_url) >>> 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:') >>> bitbucket.parse_authorization_response(redirect_response) >>> # 5. Fetch the access token >>> bitbucket.fetch_access_token(access_token_url) >>> # 6. Fetch a protected resource, i.e. user profile >>> r = bitbucket.get('https://bitbucket.org/api/1.0/user') >>> print(r.content) ``` -------------------------------- ### Run All Python Version Tests with Tox Source: https://github.com/requests/requests-oauthlib/blob/master/docs/contributing.md Execute tests across all supported Python versions using tox. Ensure all necessary Python versions are installed, preferably using a tool like pyenv. ```bash $ tox ``` -------------------------------- ### Access Protected Resource with Access Token Source: https://github.com/requests/requests-oauthlib/blob/master/docs/oauth2_workflow.md Make authenticated requests to protected resources using the obtained access token. This example fetches user profile information from Google. ```python r = oauth.get('https://www.googleapis.com/oauth2/v1/userinfo') # Enjoy =) ``` -------------------------------- ### LinkedIn OAuth 2 Authorization and Profile Fetch Source: https://github.com/requests/requests-oauthlib/blob/master/docs/examples/linkedin.md This example demonstrates the full OAuth 2 flow for LinkedIn, including obtaining authorization, fetching a token, and retrieving user profile information. Ensure environment variables and LinkedIn app settings match the code. ```python >>> # Imports >>> import os >>> from requests_oauthlib import OAuth2Session >>> # Set environment variables >>> os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' >>> # Credentials you get from registering a new application >>> client_id = '' >>> client_secret = '' >>> # LinkedIn OAuth2 requests require scope and redirect_url parameters. >>> # Ensure these values match the auth values in your LinkedIn App >>> # (see auth tab on LinkedIn Developer page) >>> scope = ['r_liteprofile'] >>> redirect_url = 'http://127.0.0.1' >>> # OAuth endpoints given in the LinkedIn API documentation >>> authorization_base_url = 'https://www.linkedin.com/oauth/v2/authorization' >>> token_url = 'https://www.linkedin.com/oauth/v2/accessToken' >>> linkedin = OAuth2Session(client_id, redirect_uri='http://127.0.0.1', scope=scope) >>> # Redirect user to LinkedIn for authorization >>> authorization_url, state = linkedin.authorization_url(authorization_base_url) >>> print(f"Please go here and authorize: {authorization_url}") >>> # Get the authorization verifier code from the callback url >>> redirect_response = input('Paste the full redirect URL here:') >>> # Fetch the access token >>> linkedin.fetch_token(token_url, client_secret=client_secret, ... include_client_id=True, ... authorization_response=redirect_response) >>> # Fetch a protected resource, i.e. user profile >>> r = linkedin.get('https://api.linkedin.com/v2/me') >>> print(r.content) ``` -------------------------------- ### Flask OAuth 2 Web App Example Source: https://github.com/requests/requests-oauthlib/blob/master/docs/examples/real_world_example.md This Flask application demonstrates the OAuth 2 web application flow. It requires setting up client ID, client secret, and authorization/token URLs. The state parameter is used for CSRF protection. ```python from requests_oauthlib import OAuth2Session from flask import Flask, request, redirect, session, url_for from flask.json import jsonify import os app = Flask(__name__) # This information is obtained upon registration of a new GitHub OAuth # application here: https://github.com/settings/applications/new client_id = "" client_secret = "" authorization_base_url = 'https://github.com/login/oauth/authorize' token_url = 'https://github.com/login/oauth/access_token' @app.route("/") def demo(): """Step 1: User Authorization. Redirect the user/resource owner to the OAuth provider (i.e. Github) using an URL with a few key OAuth parameters. """ github = OAuth2Session(client_id) authorization_url, state = github.authorization_url(authorization_base_url) # State is used to prevent CSRF, keep this for later. session['oauth_state'] = state return redirect(authorization_url) # Step 2: User authorization, this happens on the provider. @app.route("/callback", methods=["GET"]) def callback(): """ Step 3: Retrieving an access token. The user has been redirected back from the provider to your registered callback URL. With this redirection comes an authorization code included in the redirect URL. We will use that to obtain an access token. """ github = OAuth2Session(client_id, state=session['oauth_state']) token = github.fetch_token(token_url, client_secret=client_secret, authorization_response=request.url) # At this point you can fetch protected resources but lets save # the token and show how this is done from a persisted token # in /profile. session['oauth_token'] = token return redirect(url_for('.profile')) @app.route("/profile", methods=["GET"]) def profile(): """Fetching a protected resource using an OAuth 2 token. """ github = OAuth2Session(client_id, token=session['oauth_token']) return jsonify(github.get('https://api.github.com/user').json()) if __name__ == "__main__": # This allows us to use a plain HTTP callback os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = "1" app.secret_key = os.urandom(24) app.run(debug=True) ``` -------------------------------- ### Spotify OAuth 2.0 Authorization Code Flow Source: https://github.com/requests/requests-oauthlib/blob/master/docs/examples/spotify.md This example shows the complete OAuth 2.0 authorization code flow for Spotify. It includes setting up credentials, initiating the authorization request, handling the redirect, fetching the access token, and making a request to a protected resource. ```python >>> # Credentials you get from registering a new application >>> client_id = '' >>> client_secret = '' >>> redirect_uri = 'https://your.registered/callback' >>> # OAuth endpoints given in the Spotify API documentation >>> # https://developer.spotify.com/documentation/general/guides/authorization/code-flow/ >>> authorization_base_url = "https://accounts.spotify.com/authorize" >>> token_url = "https://accounts.spotify.com/api/token" >>> # https://developer.spotify.com/documentation/general/guides/authorization/scopes/ >>> scope = [ ... "user-read-email", ... "playlist-read-collaborative" ... ] >>> from requests_oauthlib import OAuth2Session >>> spotify = OAuth2Session(client_id, scope=scope, redirect_uri=redirect_uri) >>> # Redirect user to Spotify for authorization >>> authorization_url, state = spotify.authorization_url(authorization_base_url) >>> print('Please go here and authorize: ', authorization_url) >>> # Get the authorization verifier code from the callback url >>> redirect_response = input('\n\nPaste the full redirect URL here: ') >>> from requests.auth import HTTPBasicAuth >>> auth = HTTPBasicAuth(client_id, client_secret) >>> # Fetch the access token >>> token = spotify.fetch_token(token_url, auth=auth, ... authorization_response=redirect_response) >>> print(token) >>> # Fetch a protected resource, i.e. user profile >>> r = spotify.get('https://api.spotify.com/v1/me') >>> print(r.content) ``` -------------------------------- ### Mobile Application Flow: Initialize Client and Get Authorization URL Source: https://github.com/requests/requests-oauthlib/blob/master/docs/oauth2_workflow.md Initialize an OAuth2Session for the Mobile Application flow and obtain the authorization URL. Requires client ID and desired scopes. ```python >>> client_id = 'your_client_id' >>> scopes = ['scope_1', 'scope_2'] >>> auth_url = 'https://your.oauth2/auth' ``` ```python >>> from oauthlib.oauth2 import MobileApplicationClient >>> from requests_oauthlib import OAuth2Session >>> oauth = OAuth2Session(client=MobileApplicationClient(client_id=client_id), scope=scopes) >>> authorization_url, state = oauth.authorization_url(auth_url) ``` -------------------------------- ### Mobile Application Flow: Fetch Access Token Source: https://github.com/requests/requests-oauthlib/blob/master/docs/oauth2_workflow.md After obtaining the authorization URL, fetch the access token from the provider by making a GET request and processing the response URL. ```python >>> response = oauth.get(authorization_url) >>> oauth.token_from_fragment(response.url) ``` -------------------------------- ### Facebook OAuth 2 Flow with requests-oauthlib Source: https://github.com/requests/requests-oauthlib/blob/master/docs/examples/facebook.md This example demonstrates the complete OAuth 2 authorization flow for Facebook. It includes setting up credentials, initiating the authorization request, handling the redirect, fetching the access token, and making a request to a protected resource. ```python >>> # Credentials you get from registering a new application >>> client_id = '' >>> client_secret = '' >>> # OAuth endpoints given in the Facebook API documentation >>> authorization_base_url = 'https://www.facebook.com/dialog/oauth' >>> token_url = 'https://graph.facebook.com/oauth/access_token' >>> redirect_uri = 'https://localhost/' # Should match Site URL >>> from requests_oauthlib import OAuth2Session >>> from requests_oauthlib.compliance_fixes import facebook_compliance_fix >>> facebook = OAuth2Session(client_id, redirect_uri=redirect_uri) >>> facebook = facebook_compliance_fix(facebook) >>> # Redirect user to Facebook for authorization >>> authorization_url, state = facebook.authorization_url(authorization_base_url) >>> print('Please go here and authorize,', authorization_url) >>> # Get the authorization verifier code from the callback url >>> redirect_response = input('Paste the full redirect URL here:') >>> # Fetch the access token >>> facebook.fetch_token(token_url, client_secret=client_secret, ..> authorization_response=redirect_response) >>> # Fetch a protected resource, i.e. user profile >>> r = facebook.get('https://graph.facebook.com/me?') >>> print(r.content) ``` -------------------------------- ### Run GitHub Actions Locally with Act Source: https://github.com/requests/requests-oauthlib/blob/master/docs/contributing.md Execute GitHub Actions workflows locally using the 'act' tool. This is useful for testing pipeline changes without pushing to the repository. This example runs tests for pypy3.9. ```shell act -W .github/workflows/run-tests.yml -j tests --matrix python-version:pypy3.9 ``` -------------------------------- ### Build Documentation with Tox Source: https://github.com/requests/requests-oauthlib/blob/master/docs/contributing_examples.md Run the tox documentation environment to check formatting and generate the HTML output. The output can be found in docs/_build/html/index.html. ```bash tox -e docs ``` -------------------------------- ### OAuth2Session TLS Client Authentication (mTLS) Source: https://context7.com/requests/requests-oauthlib/llms.txt For OAuth 2.0 Mutual-TLS (mTLS), pass a client certificate during the token fetch process. This example shows the basic setup for initiating an OAuth2Session with a redirect URI, ready for mTLS configuration. ```python from requests_oauthlib import OAuth2Session oauth = OAuth2Session('client_id', redirect_uri='https://myapp.example/cb') ``` -------------------------------- ### Build and Validate Documentation with Tox Source: https://github.com/requests/requests-oauthlib/blob/master/docs/contributing.md Generate documentation locally using tox. After running, open the HTML files in _build/html/index.html to review changes. ```bash $ tox -e docs,readme ``` -------------------------------- ### Initialize OAuth1Session and OAuth1 Auth Helper Source: https://github.com/requests/requests-oauthlib/blob/master/docs/oauth1_workflow.md Import necessary classes and define client credentials for OAuth1 authentication. These are typically obtained after manual client signup with the OAuth provider. ```python >>> # Using OAuth1Session >>> from requests_oauthlib import OAuth1Session >>> # Using OAuth1 auth helper >>> import requests >>> from requests_oauthlib import OAuth1 >>> client_key = '...' >>> client_secret = '...' ``` -------------------------------- ### OAuth1 Authenticated GET Request Source: https://github.com/requests/requests-oauthlib/blob/master/docs/oauth1_workflow.md Use this snippet to make a GET request to a protected URL using OAuth1 authentication. Ensure you have the necessary client credentials and resource owner tokens. ```python from requests_oauthlib import OAuth1Session # Assume these variables are already defined # client_key, client_secret, resource_owner_key, resource_owner_secret, protected_url oauth = OAuth1Session(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) ``` -------------------------------- ### Google OAuth 2 Authorization and Token Fetch Source: https://github.com/requests/requests-oauthlib/blob/master/docs/examples/google.md This snippet shows the complete process of setting up an OAuth2 session with Google, redirecting the user for authorization, and fetching an access token. Ensure you have registered your application in the Google Cloud Console and obtained your client ID, client secret, and registered a callback URL. ```python >>> # Credentials you get from registering a new application >>> client_id = '' >>> client_secret = '' >>> redirect_uri = 'https://your.registered/callback' >>> # OAuth endpoints given in the Google API documentation >>> 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" ... ] >>> from requests_oauthlib import OAuth2Session >>> google = OAuth2Session(client_id, scope=scope, redirect_uri=redirect_uri) >>> # Redirect user to Google for authorization >>> authorization_url, state = google.authorization_url(authorization_base_url, ... # offline for refresh token ... # force to always make user click authorize ... access_type="offline", prompt="select_account") >>> print('Please go here and authorize:', authorization_url) >>> # Get the authorization verifier code from the callback url >>> redirect_response = input('Paste the full redirect URL here: ') >>> # Fetch the access token >>> google.fetch_token(token_url, client_secret=client_secret, ... authorization_response=redirect_response) >>> # Fetch a protected resource, i.e. user profile >>> r = google.get('https://www.googleapis.com/oauth2/v1/userinfo') >>> print(r.content) ``` -------------------------------- ### Initialize Flask App and OAuth2 Session Source: https://github.com/requests/requests-oauthlib/blob/master/docs/examples/real_world_example_with_refresh.md Sets up a Flask application and an OAuth2Session for Google. Ensure client ID, secret, and redirect URI are correctly configured. The 'offline' access type and 'select_account' prompt are used for enabling refresh tokens. ```python from pprint import pformat from time import time from flask import Flask, request, redirect, session, url_for from flask.json import jsonify import requests from requests_oauthlib import OAuth2Session app = Flask(__name__) # This information is obtained upon registration of a new Google OAuth # application at https://code.google.com/apis/console client_id = "" client_secret = "" redirect_uri = 'https://your.registered/callback' # Uncomment for detailed oauthlib logs #import logging #import sys #log = logging.getLogger('oauthlib') #log.addHandler(logging.StreamHandler(sys.stdout)) #log.setLevel(logging.DEBUG) # OAuth endpoints given in the Google API documentation authorization_base_url = "https://accounts.google.com/o/oauth2/auth" token_url = "https://accounts.google.com/o/oauth2/token" refresh_url = token_url # True for Google but not all providers. scope = [ "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile", ] @app.route("/") def demo(): """Step 1: User Authorization. Redirect the user/resource owner to the OAuth provider (i.e. Google) using an URL with a few key OAuth parameters. """ google = OAuth2Session(client_id, scope=scope, redirect_uri=redirect_uri) authorization_url, state = google.authorization_url(authorization_base_url, # offline for refresh token # force to always make user click authorize access_type="offline", prompt="select_account") # State is used to prevent CSRF, keep this for later. session['oauth_state'] = state return redirect(authorization_url) ``` -------------------------------- ### Validate Token with OAuth Provider Source: https://github.com/requests/requests-oauthlib/blob/master/docs/examples/real_world_example_with_refresh.md Validates an access token directly with the OAuth provider (Google in this case) using a simple GET request to the token info endpoint. No OAuth2Session object is required for this validation. ```python @app.route("/validate", methods=["GET"]) def validate(): """Validate a token with the OAuth provider Google. """ token = session['oauth_token'] # Defined at https://developers.google.com/accounts/docs/OAuth2LoginV1#validatingtoken validate_url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?' 'access_token=%s' % token['access_token']) # No OAuth2Session is needed, just a plain GET request return jsonify(requests.get(validate_url).json()) ``` -------------------------------- ### OAuth1 Initialization with Different Signature Types Source: https://github.com/requests/requests-oauthlib/blob/master/docs/oauth1_workflow.md Initialize OAuth1 for header, query, or body signing. Header signing is recommended. ```python import requests from requests_oauthlib import OAuth1 url = 'https://api.twitter.com/1/account/settings.json' client_key = '...' client_secret = '...' resource_owner_key = '...' resource_owner_secret = '...' ``` ```python headeroauth = OAuth1(client_key, client_secret, resource_owner_key, resource_owner_secret, signature_type='auth_header') r = requests.get(url, auth=headeroauth) ``` ```python queryoauth = OAuth1(client_key, client_secret, resource_owner_key, resource_owner_secret, signature_type='query') r = requests.get(url, auth=queryoauth) ``` ```python bodyoauth = OAuth1(client_key, client_secret, resource_owner_key, resource_owner_secret, signature_type='body') r = requests.post(url, auth=bodyoauth) ``` -------------------------------- ### Register Custom Compliance Hook for Token Response Source: https://context7.com/requests/requests-oauthlib/llms.txt Registers a custom callable to fix non-standard token responses. This example specifically handles providers that send token information as text/plain instead of JSON. ```python def fix_nonstandard_token(response): """Convert a provider's text/plain token response to proper JSON.""" import json from urllib.parse import parse_qsl if 'text/plain' in response.headers.get('content-type', ''): data = dict(parse_qsl(response.text)) data.setdefault('token_type', 'Bearer') response._content = json.dumps(data).encode() return response oauth = OAuth2Session('my_client_id') oauth.register_compliance_hook('access_token_response', fix_nonstandard_token) ``` -------------------------------- ### Skip Python Tests Requiring Environment Variables Source: https://github.com/requests/requests-oauthlib/blob/master/docs/contributing_examples.md Conditionally skip Python tests if required environment variables for identity provider configuration are not set. This prevents test failures in environments lacking the necessary setup. ```python self.client_id = os.environ.get("AUTH0_PKCE_CLIENT_ID") self.idp_domain = os.environ.get("AUTH0_DOMAIN") if not self.client_id or not self.idp_domain: self.skipTest("native auth0 is not configured properly") ``` -------------------------------- ### TLS Client Authentication with Certificate Source: https://github.com/requests/requests-oauthlib/blob/master/docs/oauth2_workflow.md Use TLS Client Authentication by passing certificate file paths to the fetch_token method. Include the client ID in the request. ```python >>> oauth.fetch_token(token_url='https://somesite.com/oauth2/token', ... include_client_id=True, cert=('test-client.pem', 'test-client-key.pem')) ``` -------------------------------- ### Legacy Application Flow (Resource Owner Password) Source: https://context7.com/requests/requests-oauthlib/llms.txt Demonstrates how to use the Resource Owner Password Credentials grant to obtain an access token by directly providing username and password. This is suitable for trusted first-party applications. ```APIDOC ## OAuth2Session — Legacy Application Flow (Resource Owner Password) The Resource Owner Password Credentials grant lets you exchange a username and password directly for an access token, suited for trusted first-party applications. ```python from oauthlib.oauth2 import LegacyApplicationClient from requests_oauthlib import OAuth2Session client_id = 'your_client_id' client_secret = 'your_client_secret' username = 'user@example.com' password = 'userpassword' token_url = 'https://somesite.com/oauth2/token' oauth = OAuth2Session(client=LegacyApplicationClient(client_id=client_id)) token = oauth.fetch_token( token_url=token_url, username=username, password=password, client_id=client_id, client_secret=client_secret ) print(token) # {'access_token': '...', 'token_type': 'Bearer', 'expires_in': 3600, ...} r = oauth.get('https://somesite.com/api/me') print(r.json()) ``` ``` -------------------------------- ### Use Pre-built Compliance Fixes (Facebook, Slack, Fitbit) Source: https://context7.com/requests/requests-oauthlib/llms.txt Applies pre-built compliance fixes for specific providers like Facebook, Slack, and Fitbit. These handle common non-standard response formats or quirks. ```python from requests_oauthlib import OAuth2Session from requests_oauthlib.compliance_fixes import ( facebook_compliance_fix, slack_compliance_fix, fitbit_compliance_fix, ) # Use a pre-built compliance fix (Facebook sends text/plain instead of JSON) session = OAuth2Session('client_id', redirect_uri='https://myapp.example/cb') session = facebook_compliance_fix(session) # Slack compliance fix example slack_session = OAuth2Session('slack_client_id') slack_session = slack_compliance_fix(slack_session) # Fitbit compliance fix (handles token expiry quirks) fitbit_session = OAuth2Session('fitbit_client_id') fitbit_session = fitbit_compliance_fix(fitbit_session) ``` -------------------------------- ### Outlook Calendar OAuth 2 Flow with requests-oauthlib Source: https://github.com/requests/requests-oauthlib/blob/master/docs/examples/outlook.md This example demonstrates the complete OAuth 2.0 authorization code flow for accessing Outlook Calendar data. Ensure you have registered your application in the Microsoft Application Registration Portal and obtained your client ID and secret. The redirect URI should match the one registered for your application. ```python >>> # This information is obtained upon registration of a new Outlook Application >>> client_id = '' >>> client_secret = '' >>> # OAuth endpoints given in Outlook API documentation >>> authorization_base_url = 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize' >>> token_url = 'https://login.microsoftonline.com/common/oauth2/v2.0/token' >>> scope = ['https://outlook.office.com/calendars.readwrite'] >>> redirect_uri = 'https://localhost/' # Should match Site URL >>> from requests_oauthlib import OAuth2Session >>> outlook = OAuth2Session(client_id,scope=scope,redirect_uri=redirect_uri) >>> # Redirect the user owner to the OAuth provider (i.e. Outlook) using an URL with a few key OAuth parameters. >>> authorization_url, state = outlook.authorization_url(authorization_base_url) >>> print('Please go here and authorize,', authorization_url) >>> # Get the authorization verifier code from the callback url >>> redirect_response = input('Paste the full redirect URL here:') >>> # Fetch the access token >>> token = outlook.fetch_token(token_url, client_secret=client_secret, authorization_response=redirect_response) >>> # Fetch a protected resource, i.e. calendar information >>> o = outlook.get('https://outlook.office.com/api/v1.0/me/calendars') >>> print(o.content) ``` -------------------------------- ### OAuth2Session - Fetch Token Source: https://context7.com/requests/requests-oauthlib/llms.txt Demonstrates how to fetch an OAuth2 token using the fetch_token method, including parameters for token URL, authorization response, client ID, and client certificates. ```APIDOC ## fetch_token() ### Description Fetches an OAuth2 token from the token URL. ### Method POST ### Endpoint `https://somesite.com/oauth2/token` ### Parameters #### Query Parameters - **include_client_id** (boolean) - Optional - Whether to include the client ID in the request. #### Request Body - **authorization_response** (string) - Required - The URL of the authorization response. - **cert** (tuple) - Optional - A tuple containing the client certificate and key paths. ### Request Example ```python token = oauth.fetch_token( token_url='https://somesite.com/oauth2/token', authorization_response='https://myapp.example/cb?code=abc123', include_client_id=True, cert=('test-client.pem', 'test-client-key.pem') # (cert, key) tuple ) print(token) ``` ### Response #### Success Response (200) - **token** (dict) - The fetched token details. ``` -------------------------------- ### Run Tests for Python 3.8 with Tox Source: https://github.com/requests/requests-oauthlib/blob/master/docs/contributing.md Use tox to create a virtual environment and run tests for a specific Python version, such as Python 3.8. ```bash $ tox -e py38 ``` -------------------------------- ### Menu Route Displaying Token and Options Source: https://github.com/requests/requests-oauthlib/blob/master/docs/examples/real_world_example_with_refresh.md Displays a success message upon obtaining an OAuth 2 token and provides links to further actions like fetching profile, refreshing tokens, or validating the token. The current token is displayed for reference. ```python @app.route("/menu", methods=["GET"]) def menu(): """""" return """

Congratulations, you have obtained an OAuth 2 token!

What would you like to do next?

    %s
    
""" % pformat(session['oauth_token'], indent=4) ``` -------------------------------- ### PKCE Flow (Native/SPA Applications) Source: https://context7.com/requests/requests-oauthlib/llms.txt Illustrates the PKCE (Proof Key for Code Exchange) flow, which enhances the Authorization Code flow for native apps and SPAs by preventing authorization code interception. PKCE is enabled by passing `pkce="S256"`. ```APIDOC ## OAuth2Session — PKCE Flow (Native/SPA Applications) PKCE (Proof Key for Code Exchange) strengthens the Authorization Code flow for native apps and SPAs where a client secret cannot be stored securely. Pass `pkce="S256"` (recommended) or `pkce="plain"` to enable it. ```python from requests_oauthlib import OAuth2Session client_id = 'YOUR_CLIENT_ID' authorization_base_url = 'https://YOUR_IDP_DOMAIN/authorize' token_url = 'https://YOUR_IDP_DOMAIN/oauth/token' redirect_uri = 'http://localhost:8080/callback' scope = ['openid', 'profile', 'email'] # PKCE is enabled by passing pkce="S256" session = OAuth2Session(client_id, scope=scope, redirect_uri=redirect_uri, pkce='S256') # authorization_url() automatically generates code_verifier + code_challenge authorization_url, state = session.authorization_url( authorization_base_url, access_type='offline' ) print('Visit:', authorization_url) redirect_response = input('Paste the full redirect URL: ') # fetch_token() automatically includes code_verifier in the request token = session.fetch_token( token_url, authorization_response=redirect_response, include_client_id=True # required when no client_secret ) print(token) # {'access_token': '...', 'id_token': '...', 'token_type': 'Bearer', ...} ``` ``` -------------------------------- ### Backend Application Flow: Fetch Access Token with Basic Auth Source: https://github.com/requests/requests-oauthlib/blob/master/docs/oauth2_workflow.md Fetch an access token for the Backend Application flow when the provider requires authentication credentials in a Basic Auth header. ```python >>> 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) ``` -------------------------------- ### OAuth2Session PKCE Flow (Native/SPA Applications) Source: https://context7.com/requests/requests-oauthlib/llms.txt This flow strengthens the Authorization Code grant for native apps and SPAs where client secrets are not secure. Enable PKCE by passing `pkce="S256"` (recommended) or `pkce="plain"`. The `authorization_url()` method generates the necessary verifier and challenge, and `fetch_token()` includes the verifier automatically. ```python from requests_oauthlib import OAuth2Session client_id = 'YOUR_CLIENT_ID' authorization_base_url = 'https://YOUR_IDP_DOMAIN/authorize' token_url = 'https://YOUR_IDP_DOMAIN/oauth/token' redirect_uri = 'http://localhost:8080/callback' scope = ['openid', 'profile', 'email'] # PKCE is enabled by passing pkce="S256" session = OAuth2Session(client_id, scope=scope, redirect_uri=redirect_uri, pkce='S256') # authorization_url() automatically generates code_verifier + code_challenge authorization_url, state = session.authorization_url( authorization_base_url, access_type='offline' ) print('Visit:', authorization_url) redirect_response = input('Paste the full redirect URL: ') # fetch_token() automatically includes code_verifier in the request token = session.fetch_token( token_url, authorization_response=redirect_response, include_client_id=True # required when no client_secret ) print(token) # {'access_token': '...', 'id_token': '...', 'token_type': 'Bearer', ...} ``` -------------------------------- ### Token Refreshing: Define Token and Credentials Source: https://github.com/requests/requests-oauthlib/blob/master/docs/oauth2_workflow.md Define the token dictionary, client ID, refresh URL, and any extra credentials needed for refreshing access tokens. The 'expires_in' value should be accurate. ```python >>> token = { ... 'access_token': 'eswfld123kjhn1v5423', ... 'refresh_token': 'asdfkljh23490sdf', ... 'token_type': 'Bearer', ... 'expires_in': '-30', # initially 3600, need to be updated by you ... } >>> client_id = r'foo' >>> refresh_url = 'https://provider.com/token' >>> protected_url = 'https://provider.com/secret' >>> # most providers will ask you for extra credentials to be passed along >>> # when refreshing tokens, usually for authentication purposes. >>> extra = { ... 'client_id': client_id, ... 'client_secret': r'potato', ... } >>> # After updating the token you will most likely want to save it. >>> def token_saver(token): ... # save token in database / session ``` -------------------------------- ### Fetch OAuth2 Token with Client Certificate Source: https://context7.com/requests/requests-oauthlib/llms.txt Fetches an OAuth2 token using client credentials and a client certificate for authentication. Ensure the cert and key files are correctly specified. ```python token = oauth.fetch_token( token_url='https://somesite.com/oauth2/token', authorization_response='https://myapp.example/cb?code=abc123', include_client_id=True, cert=('test-client.pem', 'test-client-key.pem') # (cert, key) tuple ) print(token) ``` -------------------------------- ### Legacy Application Flow: Define Credentials Source: https://github.com/requests/requests-oauthlib/blob/master/docs/oauth2_workflow.md Define the necessary credentials for the Legacy Application flow, including client ID, client secret (optional), username, and password. ```python >>> client_id = 'your_client_id' >>> client_secret = 'your_client_secret' >>> username = 'your_username' >>> password = 'your_password' ``` -------------------------------- ### Backend Application Flow: Define Credentials Source: https://github.com/requests/requests-oauthlib/blob/master/docs/oauth2_workflow.md Define the client ID and client secret required for the Backend Application flow. ```python >>> client_id = 'your_client_id' >>> client_secret = 'your_client_secret' ``` -------------------------------- ### Legacy Application Flow: Fetch Access Token Source: https://github.com/requests/requests-oauthlib/blob/master/docs/oauth2_workflow.md Fetch an access token using the Resource Owner Password Credentials Grant Type flow. Requires username and password. ```python >>> from oauthlib.oauth2 import LegacyApplicationClient >>> from requests_oauthlib import OAuth2Session >>> 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) ``` -------------------------------- ### Backend Application Flow: Fetch Access Token Source: https://github.com/requests/requests-oauthlib/blob/master/docs/oauth2_workflow.md Fetch an access token using the Resource Owner Client Credentials Grant Type flow. This is suitable for server-to-server interactions. ```python >>> from oauthlib.oauth2 import BackendApplicationClient >>> from requests_oauthlib import OAuth2Session >>> 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) ``` -------------------------------- ### Re-use saved tokens with OAuth1Session Source: https://context7.com/requests/requests-oauthlib/llms.txt Demonstrates how to re-use previously saved OAuth 1.0 tokens to make authenticated requests. Ensure you have valid tokens stored. ```python from requests_oauthlib import OAuth1Session saved_oauth = OAuth1Session(client_key, client_secret=client_secret, resource_owner_key=tokens['oauth_token'], resource_owner_secret=tokens['oauth_token_secret']) r = saved_oauth.post('http://api.twitter.com/1/statuses/update.json', data={'status': 'Hello world!'}) print(r.status_code) # 200 # Check authorization state print(saved_oauth.authorized) # True ``` -------------------------------- ### refresh_token() Method Source: https://context7.com/requests/requests-oauthlib/llms.txt Demonstrates the explicit use of the `refresh_token()` method to obtain a new access token using a refresh token. This is useful when automatic token refresh is not desired or configured. ```APIDOC ## OAuth2Session — refresh_token() `refresh_token()` explicitly fetches a new access token using a refresh token, useful when not relying on automatic refresh. ```python from requests_oauthlib import OAuth2Session oauth = OAuth2Session('client_id', token={ 'access_token': 'old_token', 'refresh_token': 'asdfkljh23490sdf', 'token_type': 'Bearer', 'expires_in': '3600', }) new_token = oauth.refresh_token( 'https://provider.com/token', refresh_token='asdfkljh23490sdf', client_id='client_id', client_secret='client_secret' ) print(new_token['access_token']) # 'new_access_token_string' ``` ``` -------------------------------- ### OAuth1Session - Re-use saved tokens Source: https://context7.com/requests/requests-oauthlib/llms.txt Demonstrates how to re-use previously saved OAuth 1.0 tokens to make authenticated requests. ```APIDOC ## OAuth1Session - Re-use saved tokens ### Description This example shows how to initialize an `OAuth1Session` with previously obtained resource owner keys and secrets to make authenticated POST requests. ### Method POST ### Endpoint `http://api.twitter.com/1/statuses/update.json` ### Request Body - **status** (string) - Required - The text of the tweet to post. ### Request Example ```python from requests_oauthlib import OAuth1Session # Assume client_key, client_secret, and tokens are already defined saved_oauth = OAuth1Session(client_key, client_secret=client_secret, resource_owner_key=tokens['oauth_token'], resource_owner_secret=tokens['oauth_token_secret']) r = saved_oauth.post('http://api.twitter.com/1/statuses/update.json', data={'status': 'Hello world!'}) print(r.status_code) # 200 # Check authorization state print(saved_oauth.authorized) # True ``` ### Response #### Success Response (200) - **status_code** (integer) - The HTTP status code of the response. - **authorized** (boolean) - Indicates if the session is currently authorized. ``` -------------------------------- ### Define OAuth 2.0 Credentials Source: https://github.com/requests/requests-oauthlib/blob/master/docs/oauth2_workflow.md Store your client ID, client secret, and redirect URI obtained from the OAuth provider. ```python client_id = r'your_client_id' client_secret = r'your_client_secret' redirect_uri = 'https://your.callback/uri' ``` -------------------------------- ### Fetch Access Token from Google Source: https://github.com/requests/requests-oauthlib/blob/master/docs/oauth2_workflow.md Exchange the authorization response obtained from the user for an access token using the provider's token endpoint. This step may require client-specific authentication. ```python token = oauth.fetch_token( 'https://accounts.google.com/o/oauth2/token', authorization_response=authorization_response, # Google specific extra parameter used for client # authentication client_secret=client_secret) ``` -------------------------------- ### OAuth1Session Full Workflow Source: https://context7.com/requests/requests-oauthlib/llms.txt Manage the complete OAuth 1.0 three-legged dance using OAuth1Session. This class handles fetching request tokens, building authorization URLs, parsing callbacks, and exchanging for access tokens. It automatically signs subsequent HTTP calls. ```python from requests_oauthlib import OAuth1Session client_key = 'your_client_key' client_secret = 'your_client_secret' request_token_url = 'https://api.twitter.com/oauth/request_token' authorization_url = 'https://api.twitter.com/oauth/authorize' access_token_url = 'https://api.twitter.com/oauth/access_token' protected_url = 'https://api.twitter.com/1/account/settings.json' # Step 1 – Fetch request token oauth = OAuth1Session(client_key, client_secret=client_secret, callback_uri='https://myapp.example/callback') request_token = oauth.fetch_request_token(request_token_url) # {'oauth_token': 'Z6eEdO8MOmk394WozF5oKyuAv855l4Mlqo7hhlSLik', # 'oauth_token_secret': 'Kd75W4OQfb2oJTV0vzGzeXftVAwgMnEK9MumzYcM'} # Step 2 – Build authorization URL and redirect user auth_redirect = oauth.authorization_url(authorization_url) print('Visit:', auth_redirect) # Step 3 – Parse the callback URL the provider redirected back to redirect_response = input('Paste the full redirect URL here: ') oauth.parse_authorization_response(redirect_response) # {'oauth_token': '...', 'oauth_token_secret': '...', 'oauth_verifier': '...'} # Step 4 – Exchange for access token tokens = oauth.fetch_access_token(access_token_url) # {'oauth_token': '6253282-eWudHldSbIaelX7swmsiHImEL4KinwaGloHANdrY', # 'oauth_token_secret': '2EEfA6BG3ly3sR3RjE0IBSnlQu4ZrUzPiYKmrkVU'} # Step 5 – Use the authorized session r = oauth.get(protected_url) print(r.json()) ``` -------------------------------- ### Backend Application Flow (Client Credentials) Source: https://context7.com/requests/requests-oauthlib/llms.txt Used for machine-to-machine authentication where no user is involved. Credentials can be sent as a Basic Auth header or in the request body. Requires client ID and secret. ```python from oauthlib.oauth2 import BackendApplicationClient from requests_oauthlib import OAuth2Session from requests.auth import HTTPBasicAuth client_id = 'your_client_id' client_secret = 'your_client_secret' token_url = 'https://provider.com/oauth2/token' # Option A: client_id/secret sent as Basic Auth header auth = HTTPBasicAuth(client_id, client_secret) client = BackendApplicationClient(client_id=client_id) oauth = OAuth2Session(client=client) token = oauth.fetch_token(token_url=token_url, auth=auth) # Option B: credentials in request body oauth2 = OAuth2Session(client=BackendApplicationClient(client_id=client_id)) token = oauth2.fetch_token(token_url=token_url, client_id=client_id, client_secret=client_secret) print(token['access_token']) # 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...' # Use the session for API calls r = oauth.get('https://provider.com/api/data') print(r.json()) ``` -------------------------------- ### Fetch Access Token using OAuth1Session and OAuth1 Auth Helper Source: https://github.com/requests/requests-oauthlib/blob/master/docs/oauth1_workflow.md Exchange the request token and verifier for an access token. This token and its secret are persistent and can be used to access protected resources until revoked. ```python >>> access_token_url = 'https://api.twitter.com/oauth/access_token' >>> # Using OAuth1Session >>> 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) { "oauth_token": "6253282-eWudHldSbIaelX7swmsiHImEL4KinwaGloHANdrY", "oauth_token_secret": "2EEfA6BG3ly3sR3RjE0IBSnlQu4ZrUzPiYKmrkVU" } >>> resource_owner_key = oauth_tokens.get('oauth_token') >>> resource_owner_secret = oauth_tokens.get('oauth_token_secret') ``` ```python >>> # Using OAuth1 auth helper >>> 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) >>> r.content "oauth_token=6253282-eWudHldSbIaelX7swmsiHImEL4KinwaGloHANdrY&oauth_token_secret=2EEfA6BG3ly3sR3RjE0IBSnlQu4ZrUzPiYKmrkVU" >>> credentials = parse_qs(r.content) >>> resource_owner_key = credentials.get('oauth_token')[0] >>> resource_owner_secret = credentials.get('oauth_token_secret')[0] ```