### Basic endpoint-mode construction example Source: https://github.com/dnplus/streamlit-oauth/blob/main/_autodocs/api-reference/oauth2component.md Example of initializing OAuth2Component in endpoint-mode using Google OAuth2 endpoints as seen in examples/google.py. ```python from streamlit_oauth import OAuth2Component oauth2 = OAuth2Component( "GOOGLE_CLIENT_ID", "GOOGLE_CLIENT_SECRET", "https://accounts.google.com/o/oauth2/v2/auth", # authorize "https://oauth2.googleapis.com/token", # token "https://oauth2.googleapis.com/token", # refresh "https://oauth2.googleapis.com/revoke", # revoke ) ``` -------------------------------- ### Client-mode construction with DiscordOAuth2 Source: https://github.com/dnplus/streamlit-oauth/blob/main/_autodocs/api-reference/oauth2component.md Example of initializing OAuth2Component in client-mode by passing a pre-configured DiscordOAuth2 client as seen in examples/discord.py. ```python from streamlit_oauth import OAuth2Component from httpx_oauth.clients.discord import DiscordOAuth2 client = DiscordOAuth2(CLIENT_ID, CLIENT_SECRET) oauth2 = OAuth2Component(client=client) ``` -------------------------------- ### Authorize with Google using OAuth2Component.authorize_button Source: https://github.com/dnplus/streamlit-oauth/blob/main/_autodocs/api-reference/oauth2component.md Initializes OAuth2Component with client credentials and endpoints, then calls authorize_button to start the OAuth flow. Requires 'openid' in scope to receive an id_token. The extras_params include prompt=consent and access_type=offline. On failure, StreamlitOauthError is caught and displayed. ```python import streamlit as st from streamlit_oauth import OAuth2Component, StreamlitOauthError oauth2 = OAuth2Component(CLIENT_ID, CLIENT_SECRET, AUTHORIZE_ENDPOINT, TOKEN_ENDPOINT, TOKEN_ENDPOINT, REVOKE_ENDPOINT) try: result = oauth2.authorize_button( name="Continue with Google", icon="https://www.google.com.tw/favicon.ico", redirect_uri="http://localhost:8501", scope="openid email profile", # must include "openid" to receive id_token key="google", extras_params={"prompt": "consent", "access_type": "offline"}, use_container_width=True, pkce='S256', ) except StreamlitOauthError as e: st.error(f"Authorization failed: {e}") else: if result: print(result["token"]) # includes id_token when scope has "openid" ``` -------------------------------- ### Basic non-forced refresh token example Source: https://github.com/dnplus/streamlit-oauth/blob/main/_autodocs/api-reference/oauth2component.md Refreshes the token only when it is expired. Uses st.session_state to store the token and reruns the app after refresh. From README.md. ```python token = st.session_state['token'] if st.button("Refresh Token"): token = oauth2.refresh_token(token) st.session_state.token = token st.rerun() ``` -------------------------------- ### Result shape of authorize_button Source: https://github.com/dnplus/streamlit-oauth/blob/main/_autodocs/types.md The structure of the dictionary returned by authorize_button, as confirmed by the example in examples/jira.py. ```python # { # "state": "...", # "code": "...", # "token": { # "access_token": "...", # "expires_in": 3600, # "token_type": "Bearer", # "scope": "read:jira-user", # "expires_at": ... # } # } ``` -------------------------------- ### Initialize and Use OAuth2Component Source: https://github.com/dnplus/streamlit-oauth/blob/main/README.md Demonstrates how to initialize the OAuth2Component with environment variables and manage the authentication flow using session state to store tokens. ```python import streamlit as st from streamlit_oauth import OAuth2Component import os # Load environment variables from .env file from dotenv import load_dotenv load_dotenv() # Set environment variables AUTHORIZE_URL = os.environ.get('AUTHORIZE_URL') TOKEN_URL = os.environ.get('TOKEN_URL') REFRESH_TOKEN_URL = os.environ.get('REFRESH_TOKEN_URL') REVOKE_TOKEN_URL = os.environ.get('REVOKE_TOKEN_URL') CLIENT_ID = os.environ.get('CLIENT_ID') CLIENT_SECRET = os.environ.get('CLIENT_SECRET') REDIRECT_URI = os.environ.get('REDIRECT_URI') SCOPE = os.environ.get('SCOPE') # Create OAuth2Component instance oauth2 = OAuth2Component(CLIENT_ID, CLIENT_SECRET, AUTHORIZE_URL, TOKEN_URL, REFRESH_TOKEN_URL, REVOKE_TOKEN_URL) # Check if token exists in session state if 'token' not in st.session_state: # If not, show authorize button result = oauth2.authorize_button("Authorize", REDIRECT_URI, SCOPE) if result and 'token' in result: # If authorization successful, save token in session state st.session_state.token = result.get('token') st.rerun() else: # If token exists in session state, show the token token = st.session_state['token'] st.json(token) if st.button("Refresh Token"): # If refresh token button is clicked, refresh the token token = oauth2.refresh_token(token) st.session_state.token = token st.rerun() ``` -------------------------------- ### _generate_pkce_pair(pkce, key=None) - Generate PKCE pair Source: https://github.com/dnplus/streamlit-oauth/blob/main/_autodocs/api-reference/streamlit_oauth.md Generates a (code_verifier, code_challenge) tuple stored in st.session_state["pkce-{key}"] once per key. The verifier is 96 bytes of URL-safe random data; the challenge is the base64url-encoded (padding stripped) SHA-256 digest of it, i.e. PKCE method S256. Any pkce value other than the exact string "S256" raises Exception("Only S256 is supported"). ```python def _generate_pkce_pair(pkce, key=None): """ generate code_verifier and code_challenge for PKCE """ pkce_key = f"pkce-{key}" if pkce != "S256": raise Exception("Only S256 is supported") if not st.session_state.get(pkce_key): code_verifier = secrets.token_urlsafe(96) code_challenge = base64.urlsafe_b64encode(hashlib.sha256(code_verifier.encode()).digest()).decode().replace("=", "") st.session_state[pkce_key] = (code_verifier, code_challenge) return st.session_state[pkce_key] ``` -------------------------------- ### OAuth2Component.__init__ Source: https://github.com/dnplus/streamlit-oauth/blob/main/_autodocs/api-reference/oauth2component.md Constructor for the OAuth2Component class. Supports two mutually exclusive modes: endpoint-mode (pass client_id, client_secret, and provider endpoints) or client-mode (pass a pre-configured httpx_oauth client). When client is given, all other constructor arguments are ignored. ```APIDOC ## OAuth2Component.__init__ ### Description Constructor for the OAuth2Component class. Supports two mutually exclusive modes: endpoint-mode (pass client_id, client_secret, and provider endpoints) or client-mode (pass a pre-configured httpx_oauth client). When client is given, all other constructor arguments are ignored. ### Method Constructor ### Signature ```python def __init__(self, client_id=None, client_secret=None, authroize_endpoint=None, token_endpoint=None, refresh_token_endpoint=None, revoke_token_endpoint=None, client=None, *, authorize_endpoint=None, token_endpoint_auth_method: OAuth2ClientAuthMethod = "client_secret_basic", revocation_endpoint_auth_method: OAuth2ClientAuthMethod = "client_secret_basic"): ``` ### Parameters - **client_id** (str) - Optional - OAuth2 client id issued by the authorization server. Ignored if client is given. - **client_secret** (str) - Optional - OAuth2 client secret. Ignored if client is given. - **authroize_endpoint** (str) - Optional - The authorization endpoint URL. Deprecated typo, kept for backwards compatibility; superseded by authorize_endpoint (keyword-only). - **token_endpoint** (str) - Optional - The token endpoint URL. - **refresh_token_endpoint** (str) - Optional - The refresh token endpoint URL (often identical to token_endpoint). - **revoke_token_endpoint** (str) - Optional - The revoke token endpoint URL. - **client** (BaseOAuth2) - Optional - Pre-built httpx_oauth OAuth2 client. If specified, the other arguments are ignored. - **authorize_endpoint** (str, keyword-only) - Optional - Corrected spelling of the authorization endpoint. Resolved as authorize_endpoint or authroize_endpoint. - **token_endpoint_auth_method** (OAuth2ClientAuthMethod, keyword-only) - Optional, default "client_secret_basic" - Client authentication method used at the token endpoint; forwarded to httpx_oauth.OAuth2. - **revocation_endpoint_auth_method** (OAuth2ClientAuthMethod, keyword-only) - Optional, default "client_secret_basic" - Client authentication method used at the revoke endpoint; forwarded to httpx_oauth.OAuth2. ### Return Type None. Stores the resolved client on self.client. ### Throws/Rejects None explicitly in the constructor itself. If client is None and required endpoint/credential arguments are missing, the error surfaces lazily when the first network call is made by httpx_oauth. ### Examples #### Endpoint-mode construction (examples/google.py) ```python from streamlit_oauth import OAuth2Component oauth2 = OAuth2Component( "GOOGLE_CLIENT_ID", "GOOGLE_CLIENT_SECRET", "https://accounts.google.com/o/oauth2/v2/auth", # authorize "https://oauth2.googleapis.com/token", # token "https://oauth2.googleapis.com/token", # refresh "https://oauth2.googleapis.com/revoke", # revoke ) ``` #### Client-mode construction with a provider-specific client (examples/discord.py) ```python from streamlit_oauth import OAuth2Component from httpx_oauth.clients.discord import DiscordOAuth2 client = DiscordOAuth2(CLIENT_ID, CLIENT_SECRET) oauth2 = OAuth2Component(client=client) ``` ``` -------------------------------- ### Guard against PKCE misconfiguration Source: https://github.com/dnplus/streamlit-oauth/blob/main/_autodocs/errors.md Use to validate the pkce parameter before calling authorize_button. The package only supports pkce='S256'; any other truthy value raises Exception with message 'Only S256 is supported'. This guard raises ValueError instead. ```python # PKCE misconfiguration guard if pkce and pkce != "S256": raise ValueError("streamlit-oauth only supports pkce='S256'") ``` -------------------------------- ### OAuth2Component constructor Source: https://github.com/dnplus/streamlit-oauth/blob/main/README.md Creates an OAuth2Component instance with the provided client credentials and endpoint URLs. The constructor accepts either individual parameters or an httpx_oauth client. ```APIDOC ## OAuth2Component(client_id, client_secret, authorize_endpoint, token_endpoint, refresh_token_endpoint, revoke_token_endpoint) ### Description Creates an OAuth2Component instance for handling OAuth2 authorization flows. ### Parameters - **client_id** (string) - Required - The OAuth2 client id provided by the authorization server. - **client_secret** (string) - Required - The OAuth2 client secret provided by the authorization server. - **authorize_endpoint** (string) - Required - The authorization endpoint URL of the OAuth2 server. - **token_endpoint** (string) - Required - The token endpoint URL of the OAuth2 server. - **refresh_token_endpoint** (string) - Required - The refresh token endpoint URL of the OAuth2 server. - **revoke_token_endpoint** (string) - Required - The revoke token endpoint URL of the OAuth2 server. - **client** (object) - Optional - The httpx_oauth client to be used for the requests, default is None, if specified other arguments will be ignored. ### Notes - The parameter `authroize_endpoint` is deprecated due to a typo; use `authorize_endpoint` instead. ``` -------------------------------- ### Constructing the OAuth2 client Source: https://github.com/dnplus/streamlit-oauth/blob/main/_autodocs/types.md The default client class is constructed in OAuth2Component.__init__ when the client argument is None. ```python self.client = OAuth2( client_id, client_secret, authorize_endpoint, token_endpoint, refresh_token_endpoint=refresh_token_endpoint, revoke_token_endpoint=revoke_token_endpoint, token_endpoint_auth_method=token_endpoint_auth_method, revocation_endpoint_auth_method=revocation_endpoint_auth_method, ) ``` -------------------------------- ### authorize_button(name, redirect_uri, scope, height=800, width=600, key=None, extras_params={}, pkce=None, use_container_width=False, icon=None) Source: https://github.com/dnplus/streamlit-oauth/blob/main/README.md Generates an HTML button that initiates the OAuth2 authorization code grant flow. The button opens a popup window that prompts the user to authorize the application. ```APIDOC ## authorize_button(name, redirect_uri, scope, height=800, width=600, key=None, extras_params={}, pkce=None, use_container_width=False, icon=None) ### Description Generates an HTML button that initiates the OAuth2 authorization code grant flow. The button opens a popup window that prompts the user to authorize the application. ### Parameters - **name** (string) - Required - The name to be displayed on the button. - **redirect_uri** (string) - Required - The URL where the authorization server will redirect the user after the authorization process is completed. - **scope** (string) - Required - The OAuth2 scopes required by the application. - **height** (integer) - Optional - The height of the popup window. Default is 800. - **width** (integer) - Optional - The width of the popup window. Default is 600. - **key** (string) - Optional - The unique key of the button component. - **extra_params** (dictionary) - Optional - A dictionary containing extra parameters to be sent to the authorization server. - **pkce** (string) - Optional - Accept value `S256` indicating whether to use PKCE (Proof Key for Code Exchange) for the authorization code grant flow. - **use_container_width** (boolean) - Optional - If `True`, set the button width to the container width. - **icon** (string) - Optional - The icon to be displayed on the button. - **auto_click** (boolean) - Optional - If `True`, the button will be clicked automatically. ### Returns - A dictionary containing the authorization code or access token object, depending on the flow. ``` -------------------------------- ### OAuth2Component __init__ signature Source: https://github.com/dnplus/streamlit-oauth/blob/main/_autodocs/api-reference/oauth2component.md The constructor signature for OAuth2Component, showing available parameters for endpoint-mode and client-mode configuration. ```python def __init__(self, client_id=None, client_secret=None, authroize_endpoint=None, token_endpoint=None, refresh_token_endpoint=None, revoke_token_endpoint=None, client=None, *, authorize_endpoint=None, token_endpoint_auth_method: OAuth2ClientAuthMethod = "client_secret_basic", revocation_endpoint_auth_method: OAuth2ClientAuthMethod = "client_secret_basic": ``` -------------------------------- ### Basic revocation with session cleanup Source: https://github.com/dnplus/streamlit-oauth/blob/main/_autodocs/api-reference/oauth2component.md Revokes the token and clears the session state. From README.md dev-mode sample, mirrored in examples/google.py. ```python if st.button("🗑 Revoke Token"): oauth2.revoke_token(token) del st.session_state.token st.rerun() ``` -------------------------------- ### Basic OAuth2 authorization flow Source: https://github.com/dnplus/streamlit-oauth/blob/main/_autodocs/api-reference/oauth2component.md A basic implementation of the authorize_button method to retrieve and store an OAuth2 token, as seen in examples/yandex.py. ```python import streamlit as st from streamlit_oauth import OAuth2Component oauth2 = OAuth2Component(CLIENT_ID, CLIENT_SECRET, AUTHORIZE_URL, TOKEN_URL, REFRESH_TOKEN_URL, REVOKE_TOKEN_URL) if 'token' not in st.session_state: result = oauth2.authorize_button("Authorize", REDIRECT_URI, SCOPE) if result and 'token' in result: st.session_state.token = result.get('token') st.rerun() ``` -------------------------------- ### Import OAuth2Component, StreamlitOauthError, and OAuth2 Source: https://github.com/dnplus/streamlit-oauth/blob/main/_autodocs/api-reference/streamlit_oauth.md Import the main component class, the custom exception, and the OAuth2 base class from httpx_oauth. This is the standard import path for using the streamlit_oauth package. ```python from streamlit_oauth import OAuth2Component, StreamlitOauthError, OAuth2 ``` -------------------------------- ### OAuth2Component.authorize_button Source: https://github.com/dnplus/streamlit-oauth/blob/main/_autodocs/api-reference/oauth2component.md Initiates the OAuth2 authorization flow by displaying a button. When clicked, it redirects the user to the authorization endpoint and handles the callback to obtain tokens. ```APIDOC ## OAuth2Component.authorize_button ### Description Initiates the OAuth2 authorization flow by displaying a button. When clicked, it redirects the user to the authorization endpoint and handles the callback to obtain tokens. ### Method N/A (Python method) ### Endpoint N/A (Python method) ### Parameters - **name** (str) - Required - The label of the button. - **icon** (str) - Optional - URL of an icon to display on the button. - **redirect_uri** (str) - Required - The URI to redirect to after authorization. - **scope** (str) - Required - Space-separated list of OAuth2 scopes. Must include "openid" to receive an id_token. - **key** (str) - Optional - A unique key for the button widget. - **extras_params** (dict) - Optional - Additional query parameters to include in the authorization request. - **use_container_width** (bool) - Optional - Whether to use the full container width for the button. - **pkce** (str) - Optional - PKCE code challenge method, e.g., "S256". ### Request Example ```python result = oauth2.authorize_button( name="Continue with Google", icon="https://www.google.com.tw/favicon.ico", redirect_uri="http://localhost:8501", scope="openid email profile", key="google", extras_params={"prompt": "consent", "access_type": "offline"}, use_container_width=True, pkce='S256', ) ``` ### Response #### Success Response - **result** (dict) - Contains the token dictionary, including id_token when scope includes "openid". #### Response Example ```python print(result["token"]) # includes id_token when scope has "openid" ``` ### Errors - **StreamlitOauthError** - Raised when authorization fails. ``` -------------------------------- ### authorize_button method signature Source: https://github.com/dnplus/streamlit-oauth/blob/main/_autodocs/api-reference/oauth2component.md The method signature for initiating the OAuth2 authorization code grant flow. ```python def authorize_button(self, name, redirect_uri, scope, height=800, width=600, key=None, pkce=None, extras_params={}, icon=None, use_container_width=False, auto_click=False): ``` -------------------------------- ### _generate_state(key=None) - Generate CSRF state Source: https://github.com/dnplus/streamlit-oauth/blob/main/_autodocs/api-reference/streamlit_oauth.md Generates a hex CSRF/state value stored in st.session_state["state-{key}"] once per key. The docstring claims a 5-minute persistence window, but the source implements no expiry; the value is kept until authorize_button deletes it after a completed flow. Used to keep state hashes identical across reruns. ```python def _generate_state(key=None): """ persist state for 300 seconds (5 minutes) to keep component state hash the same """ state_key = f"state-{key}" if not st.session_state.get(state_key): st.session_state[state_key] = uuid.uuid4().hex return st.session_state[state_key] ``` -------------------------------- ### Import OAuth2ClientAuthMethod Source: https://github.com/dnplus/streamlit-oauth/blob/main/_autodocs/types.md The OAuth2ClientAuthMethod alias is re-exported at the module level for use in OAuth2 configurations. ```python from httpx_oauth.oauth2 import OAuth2, OAuth2ClientAuthMethod ``` -------------------------------- ### Declare authorize_button component Source: https://github.com/dnplus/streamlit-oauth/blob/main/_autodocs/api-reference/streamlit_oauth.md The component is declared conditionally based on the _RELEASE flag to toggle between a local development server and the pre-built frontend. ```python _RELEASE = False # comment out the following line to use the local dev server # use streamlit run __init__.py --server.enableCORS=false to run the local dev server _RELEASE = True if not _RELEASE: _authorize_button = components.declare_component( "authorize_button", url="http://localhost:3000", # vite dev server port ) else: parent_dir = os.path.dirname(os.path.abspath(__file__)) build_dir = os.path.join(parent_dir, "frontend/dist") _authorize_button = components.declare_component("authorize_button", path=build_dir) ``` -------------------------------- ### Handle expired token without refresh_token Source: https://github.com/dnplus/streamlit-oauth/blob/main/_autodocs/errors.md Use when refresh_token fails because the token is expired and has no refresh_token key. The exception message is 'Token is expired and no refresh token is available'. Catch Exception and treat as session expiry, then re-run authorize_button. ```python token = {"access_token": "...", "expires_at": 1700000000} # expired, no refresh_token try: new_token = oauth2.refresh_token(token, force=True) except Exception as e: # "Token is expired and no refresh token is available" # -> treat as session expiry, re-run authorize_button del st.session_state.token ``` -------------------------------- ### Revoke refresh token instead of access token Source: https://github.com/dnplus/streamlit-oauth/blob/main/_autodocs/api-reference/oauth2component.md Calls revoke_token with token_type_hint='refresh_token' to revoke the refresh token instead of the access token. ```python oauth2.revoke_token(token, token_type_hint="refresh_token") ``` -------------------------------- ### Declare OAuth2 authorize_button component Source: https://github.com/dnplus/streamlit-oauth/blob/main/_autodocs/api-reference/oauth2component.md The authorize_button component is declared at the module level using the Streamlit components API, pointing to the frontend build directory. ```python _authorize_button = components.declare_component("authorize_button", path=build_dir) ``` -------------------------------- ### Forced refresh token with error handling Source: https://github.com/dnplus/streamlit-oauth/blob/main/_autodocs/api-reference/oauth2component.md Forces a token refresh even if not expired. Requires offline scope to receive a refresh_token. Catches exceptions, including the plain Exception 'Token is expired and no refresh token is available'. ```python import time from streamlit_oauth import StreamlitOauthError # offline scope required, otherwise the provider may not return a refresh_token try: token = oauth2.refresh_token(token, force=True) except Exception as e: st.error(f"Refresh failed: {e}") # e.g. "Token is expired and no refresh token is available" else: st.session_state.token = token st.rerun() ``` -------------------------------- ### refresh_token(token, force=False) Source: https://github.com/dnplus/streamlit-oauth/blob/main/README.md Refreshes the access token using the refresh token. If the token is not expired, the function returns the same token. ```APIDOC ## refresh_token(token, force=False) ### Description Refreshes the access token using the refresh token. If the token is not expired, the function returns the same token. ### Parameters - **token** (object) - Required - The access token object to be refreshed. - **force** (boolean) - Optional - A boolean value that forces the refresh token to be used, even if the access token is not expired. Default is False. ### Returns - A dictionary containing the new access token or the same access token if it has not expired. ``` -------------------------------- ### Catch StreamlitOauthError in a Streamlit app Source: https://github.com/dnplus/streamlit-oauth/blob/main/_autodocs/errors.md Shows how to catch StreamlitOauthError when calling authorize_button. It distinguishes between a provider error (args[0] is a dict) and a state mismatch (args[0] is a string). ```python import streamlit as st from streamlit_oauth import OAuth2Component, StreamlitOauthError oauth2 = OAuth2Component(CLIENT_ID, CLIENT_SECRET, AUTHORIZE_URL, TOKEN_URL) try: result = oauth2.authorize_button("Authorize", REDIRECT_URI, "openid profile") except StreamlitOauthError as e: if isinstance(e.args[0], dict): # provider error (condition 1) st.error(f"Provider rejected the request: {e.args[0].get('error')}") else: # state mismatch (condition 2) st.error("State mismatch — the authorization response is stale or tampered with.") ``` -------------------------------- ### refresh_token method signature Source: https://github.com/dnplus/streamlit-oauth/blob/main/_autodocs/api-reference/oauth2component.md Signature of the refresh_token method. It refreshes the token if expired or when force is True. Returns the same token if no refresh occurs. ```python def refresh_token(self, token, force=False): ``` -------------------------------- ### revoke_token(token, token_type_hint='access_token') Source: https://github.com/dnplus/streamlit-oauth/blob/main/README.md Revokes the provided token. Returns a boolean indicating whether the revocation was successful. ```APIDOC ## revoke_token(token, token_type_hint='access_token') ### Description Revokes the provided token. Returns a boolean indicating whether the revocation was successful. ### Parameters - **token** (object) - Required - The access token object to be revoked. - **token_type_hint** (string) - Optional - A hint about the type of the token submitted for revocation. Default is 'access_token'. ### Returns - A boolean value indicating whether the token was revoked successfully. ``` -------------------------------- ### OAuth2Component.revoke_token Source: https://github.com/dnplus/streamlit-oauth/blob/main/_autodocs/api-reference/oauth2component.md Revokes the token at the revoke_token_endpoint. Always returns True, as exceptions are silently discarded. ```APIDOC ## OAuth2Component.revoke_token ### Description Revokes the token at the revoke_token_endpoint. Always returns True, as exceptions are silently discarded. ### Method N/A (Python method) ### Endpoint N/A (Python method) ### Parameters - **token** (dict) - Required - Token dictionary. Its access_token (or refresh_token, per the hint) value is revoked. - **token_type_hint** (str) - Optional - Either "access_token" or "refresh_token", selecting which key of the token dict is sent for revocation. Default is "access_token". ### Request Example ```python if st.button("🗑 Revoke Token"): oauth2.revoke_token(token) del st.session_state.token st.rerun() ``` ### Response #### Success Response - **bool** - Always True. #### Response Example ```python oauth2.revoke_token(token, token_type_hint="refresh_token") ``` ### Errors Does not raise: all exceptions from the revoke call are swallowed. ``` -------------------------------- ### OAuth2Component.refresh_token Source: https://github.com/dnplus/streamlit-oauth/blob/main/_autodocs/api-reference/oauth2component.md Refreshes an OAuth2 token if it is expired, or if force is True. Returns the same token if no refresh occurs. ```APIDOC ## OAuth2Component.refresh_token ### Description Refreshes an OAuth2 token if it is expired, or if force is True. Returns the same token if no refresh occurs. ### Method N/A (Python method) ### Endpoint N/A (Python method) ### Parameters - **token** (dict) - Required - The token dictionary, typically stored in st.session_state. Inspected via token.get('expires_at') and token.get('refresh_token'). - **force** (bool) - Optional - If True, refresh even when the token is not expired. Default is False. ### Request Example ```python token = st.session_state['token'] if st.button("Refresh Token"): token = oauth2.refresh_token(token) st.session_state.token = token st.rerun() ``` ### Response #### Success Response - **dict** - The same token object when no refresh occurred; the new token dict otherwise. The returned dict always contains a refresh_token key after a refresh. #### Response Example ```python token = oauth2.refresh_token(token, force=True) ``` ### Errors - **Exception** - Raised when token is expired and no refresh token is available. Message: "Token is expired and no refresh token is available". - **network errors** - Propagated from httpx_oauth's refresh_token (e.g., invalid/revoked refresh token). ``` -------------------------------- ### Define StreamlitOauthError exception class Source: https://github.com/dnplus/streamlit-oauth/blob/main/_autodocs/errors.md The custom exception class defined in streamlit_oauth/__init__.py. It is a direct subclass of Exception with no additional attributes or behaviors. ```python class StreamlitOauthError(Exception): """ Exception raised from streamlit-oauth. """ ``` -------------------------------- ### revoke_token method signature Source: https://github.com/dnplus/streamlit-oauth/blob/main/_autodocs/api-reference/oauth2component.md Signature of the revoke_token method. Revokes the token at the revoke_token_endpoint. The token_type_hint selects which key of the token dict is sent for revocation. ```python def revoke_token(self, token, token_type_hint="access_token"): ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.