Reuse user tokens with UserAuthenticationStorageHelper#

In this tutorial, we will look at different ways to use UserAuthenticationStorageHelper.

Basic Use Case#

This is the most basic example on how to use this helper. It will store any generated token in a file named user_token.json in your current folder and automatically update that file with refreshed tokens. Should the file not exists, the auth scope not match the one of the stored auth token or the token + refresh token no longer be valid, it will use UserAuthenticator to generate a new one.

 1 from twitchAPI import Twitch
 2 from twitchAPI.oauth import UserAuthenticationStorageHelper
 3 from twitchAPI.types import AuthScope
 4
 5 APP_ID = 'my_app_id'
 6 APP_SECRET = 'my_app_secret'
 7 USER_SCOPE = [AuthScope.CHAT_READ, AuthScope.CHAT_EDIT]
 8
 9
10 async def run():
11     twitch = await Twitch(APP_ID, APP_SECRET)
12     helper = UserAuthenticationStorageHelper(twitch, USER_SCOPE)
13     await helper.bind()
14     # do things
15
16     await twitch.close()
17
18
19 # lets run our setup
20 asyncio.run(run())

Use a different file to store your token#

You can specify a different file in which the token should be stored in like this:

 1 from twitchAPI import Twitch
 2 from twitchAPI.oauth import UserAuthenticationStorageHelper
 3 from twitchAPI.types import AuthScope
 4 from pathlib import PurePath
 5
 6 APP_ID = 'my_app_id'
 7 APP_SECRET = 'my_app_secret'
 8 USER_SCOPE = [AuthScope.CHAT_READ, AuthScope.CHAT_EDIT]
 9
10
11 async def run():
12     twitch = await Twitch(APP_ID, APP_SECRET)
13     helper = UserAuthenticationStorageHelper(twitch,
14                                              USER_SCOPE,
15                                              storage_path=PurePath('/my/new/path/file.json'))
16     await helper.bind()
17     # do things
18
19     await twitch.close()
20
21
22 # lets run our setup
23 asyncio.run(run())

Use custom token generation code#

Sometimes (for example for headless setups), the default UserAuthenticator is not good enough. For these cases, you can use your own function.

 1 from twitchAPI import Twitch
 2 from twitchAPI.oauth import UserAuthenticationStorageHelper
 3 from twitchAPI.types import AuthScope
 4
 5 APP_ID = 'my_app_id'
 6 APP_SECRET = 'my_app_secret'
 7 USER_SCOPE = [AuthScope.CHAT_READ, AuthScope.CHAT_EDIT]
 8
 9
10 async def my_token_generator(twitch: Twitch, target_scope: List[AuthScope]) -> (str, str):
11     # generate new token + refresh token here and return it
12     return 'token', 'refresh_token'
13
14 async def run():
15     twitch = await Twitch(APP_ID, APP_SECRET)
16     helper = UserAuthenticationStorageHelper(twitch,
17                                              USER_SCOPE,
18                                              auth_generator_func=my_token_generator)
19     await helper.bind()
20     # do things
21
22     await twitch.close()
23
24
25 # lets run our setup
26 asyncio.run(run())