User OAuth Authenticator and helper functions#

User Authenticator#

UserAuthenticator is an alternative to various online services that give you a user auth token. It provides non-server and server options.

Requirements for non-server environment#

Since this tool opens a browser tab for the Twitch authentication, you can only use this tool on environments that can open a browser window and render the twitch.tv website.

For my authenticator you have to add the following URL as a “OAuth Redirect URL”: http://localhost:17563 You can set that here in your twitch dev dashboard.

Requirements for server environment#

You need the user code provided by Twitch when the user logs-in at the url returned by return_auth_url().

Create the UserAuthenticator with the URL of your webserver that will handle the redirect, and add it as a “OAuth Redirect URL” You can set that here in your twitch dev dashboard.

See also

This tutorial has a more detailed example how to use UserAuthenticator on a headless server: Generate a User Auth Token Headless

See also

You may also use the CodeFlow to generate your access token headless CodeFlow

Code example#

from twitchAPI.twitch import Twitch
from twitchAPI.oauth import UserAuthenticator
from twitchAPI.type import AuthScope

twitch = await Twitch('my_app_id', 'my_app_secret')

target_scope = [AuthScope.BITS_READ]
auth = UserAuthenticator(twitch, target_scope, force_verify=False)
# this will open your default browser and prompt you with the twitch verification website
token, refresh_token = await auth.authenticate()
# add User authentication
await twitch.set_user_authentication(token, target_scope, refresh_token)

User Authentication Storage Helper#

UserAuthenticationStorageHelper provides a simplified way to store & reuse user tokens.

Code example#

twitch = await Twitch(APP_ID, APP_SECRET)
helper = UserAuthenticationStorageHelper(twitch, TARGET_SCOPES)
await helper.bind()"

See also

See Reuse user tokens with UserAuthenticationStorageHelper for more information.

Class Documentation#

async twitchAPI.oauth.refresh_access_token(refresh_token, app_id, app_secret, session=None, auth_base_url='https://id.twitch.tv/oauth2/')#

Simple helper function for refreshing a user access token.

Parameters:
  • refresh_token (str) – the current refresh_token

  • app_id (str) – the id of your app

  • app_secret (str) – the secret key of your app

  • session (ClientSession) – optionally a active client session to be used for the web request to avoid having to open a new one

  • auth_base_url (str) – The URL to the Twitch API auth server

Returns:

access_token, refresh_token

Raises:
Return type:

(str, str)

async twitchAPI.oauth.validate_token(access_token, session=None, auth_base_url='https://id.twitch.tv/oauth2/')#

Helper function for validating a user or app access token.

https://dev.twitch.tv/docs/authentication/validate-tokens

Parameters:
  • access_token (str) – either a user or app OAuth access token

  • session (Optional[ClientSession]) – optionally a active client session to be used for the web request to avoid having to open a new one

  • auth_base_url (str) – The URL to the Twitch API auth server

Return type:

dict

Returns:

response from the api

async twitchAPI.oauth.get_user_info(access_token, session=None, auth_base_url='https://id.twitch.tv/oauth2/')#

Helper function to get claims information from an OAuth2 access token.

https://dev.twitch.tv/docs/authentication/getting-tokens-oidc/#getting-claims-information-from-an-access-token

Parameters:
  • access_token (str) – a OAuth2 access token

  • session (Optional[ClientSession]) – optionally a active client session to be used for the web request to avoid having to open a new one

  • auth_base_url (str) – The URL to the Twitch API auth server

Return type:

dict

Returns:

response from the API

async twitchAPI.oauth.revoke_token(client_id, access_token, session=None, auth_base_url='https://id.twitch.tv/oauth2/')#

Helper function for revoking a user or app OAuth access token.

https://dev.twitch.tv/docs/authentication/revoke-tokens

Parameters:
  • client_id (str) – client id belonging to the access token

  • access_token (str) – user or app OAuth access token

  • session (ClientSession) – optionally a active client session to be used for the web request to avoid having to open a new one

  • auth_base_url (str) – The URL to the Twitch API auth server

Return type:

bool

Returns:

True if revoking succeeded, otherwise False

class twitchAPI.oauth.CodeFlow#

Bases: object

Basic implementation of the CodeFlow User Authentication.

Example use:

APP_ID = "my_app_id"
APP_SECRET = "my_app_secret"
USER_SCOPES = [AuthScope.BITS_READ, AuthScope.BITS_WRITE]

twitch = await Twitch(APP_ID, APP_SECRET)
code_flow = CodeFlow(twitch, USER_SCOPES)
code, url = await code_flow.get_code()
print(url)  # visit this url and complete the flow
token, refresh = await code_flow.wait_for_auth_complete()
await twitch.set_user_authentication(token, USER_SCOPES, refresh)
__init__(twitch, scopes, auth_base_url='https://id.twitch.tv/oauth2/')#
Parameters:
logger: Logger#

The logger used for OAuth related log messages

async get_code()#

Requests a Code and URL from teh API to start the flow

Return type:

(str, str)

Returns:

The Code and URL used to further the flow

async wait_for_auth_complete()#

Waits till the user completed the flow on teh website and then generates the tokens.

Return type:

(str, str)

Returns:

the generated access_token and refresh_token

class twitchAPI.oauth.UserAuthenticator#

Bases: object

Simple to use client for the Twitch User authentication flow.

__init__(twitch, scopes, force_verify=False, url='http://localhost:17563', host='0.0.0.0', port=17563, auth_base_url='https://id.twitch.tv/oauth2/')#
Parameters:
  • twitch (Twitch) – A twitch instance

  • scopes (List[AuthScope]) – List of the desired Auth scopes

  • force_verify (bool) – If this is true, the user will always be prompted for authorization by twitch

    Default: False

  • url (str) – The reachable URL that will be opened in the browser.

    Default: http://localhost:17563

  • host (str) – The host the webserver will bind to.

    Default: 0.0.0.0

  • port (int) – The port that will be used for the webserver.

    Default: 17653

  • auth_base_url (str) – The URL to the Twitch API auth server

logger: Logger#

The logger used for OAuth related log messages

document: str#

The document that will be rendered at the end of the flow

port: int#

The port that will be used for the webserver.

Default: 17653

host: str#

The host the webserver will bind to.

Default: 0.0.0.0

state: str#

The state to be used for identification,

Default: a random UUID

stop()#

Manually stop the flow

Return type:

None

return_auth_url()#

Returns the URL that will authenticate the app, used for headless server environments.

async mock_authenticate(user_id)#

Authenticate with a mocked auth flow via twitch-cli

For more info see Mocking with twitch-cli

Parameters:

user_id (str) – the id of the user to generate a auth token for

Return type:

str

Returns:

the user auth token

async authenticate(callback_func=None, user_token=None, browser_name=None, browser_new=2, use_browser=True, auth_url_callback=None)#

Start the user authentication flow

If callback_func is not set, authenticate will wait till the authentication process finished and then return the access_token and the refresh_token If user_token is set, it will be used instead of launching the webserver and opening the browser

Parameters:
  • callback_func (Optional[Callable[[str, str], None]]) – Function to call once the authentication finished.

  • user_token (Optional[str]) – Code obtained from twitch to request the access and refresh token.

  • browser_name (Optional[str]) – The browser that should be used, None means that the system default is used. See the webbrowser documentation for more info

    Default:None

  • browser_new (int) – controls in which way the link will be opened in the browser. See the webbrowser documentation for more info

    Default:2

  • use_browser (bool) – controls if a browser should be opened. If set to False, the browser will not be opened and the URL to be opened will either be printed to the info log or send to the specified callback function (controlled by auth_url_callback)

    Default:True

  • auth_url_callback (Optional[Callable[[str], Awaitable[None]]]) – a async callback that will be called with the url to be used for the authentication flow should use_browser be False. If left as None, the URL will instead be printed to the info log

    Default:None

Returns:

None if callback_func is set, otherwise access_token and refresh_token

Raises:

TwitchAPIException – if authentication fails

Return type:

None or (str, str)

class twitchAPI.oauth.UserAuthenticationStorageHelper#

Bases: object

Helper for automating the generation and storage of a user auth token.

See Reuse user tokens with UserAuthenticationStorageHelper for more detailed examples and use cases.

Basic example use:

twitch = await Twitch(APP_ID, APP_SECRET)
helper = UserAuthenticationStorageHelper(twitch, TARGET_SCOPES)
await helper.bind()
__init__(twitch, scopes, storage_path=None, auth_generator_func=None, auth_base_url='https://id.twitch.tv/oauth2/')#
logger: Logger#

The logger used for OAuth Storage Helper related log messages

async bind()#

Bind the helper to the provided instance of twitch and sets the user authentication.