outlook-oauth-hack/refresh_token.py

44 lines
1.3 KiB
Python
Raw Normal View History

2024-04-05 18:13:16 -04:00
#! /usr/bin/env python3
from msal import ConfidentialClientApplication, SerializableTokenCache
import config
import sys
2024-04-05 18:47:33 -04:00
print_access_token = True
2024-04-05 18:47:33 -04:00
# get first command line argument
if len(sys.argv) > 1:
profile = sys.argv[1]
else:
sys.exit("Please provide a profile name as the first argument.")
2024-04-05 18:47:33 -04:00
profile_config = config.get_config(profile)
# We use the cache to extract the refresh token
cache = SerializableTokenCache()
2024-04-05 18:47:33 -04:00
app = ConfidentialClientApplication(profile_config.ClientId, client_credential=profile_config.ClientSecret, token_cache=cache, authority=profile_config.Authority)
2024-04-05 18:47:33 -04:00
# check if file exists and error out if it doesn't
try:
old_refresh_token = open(profile_config.RefreshTokenFileName,'r').read()
except FileNotFoundError:
sys.exit("Please get the initial token by running `o365-get-token` first.")
2024-04-05 18:47:33 -04:00
token = app.acquire_token_by_refresh_token(old_refresh_token,profile_config.Scopes)
if 'error' in token:
print(token)
sys.exit("Failed to get access token")
# you're supposed to save the old refresh token each time
2024-04-05 18:47:33 -04:00
with open(profile_config.RefreshTokenFileName, 'w') as f:
#f.write(cache.find('RefreshToken')[0]['secret'])
f.write(token['refresh_token'])
2024-04-05 18:47:33 -04:00
with open(profile_config.AccessTokenFileName, 'w') as f:
f.write(token['access_token'])
if print_access_token:
print(token['access_token'])