Skip to content

Instantly share code, notes, and snippets.

@radiocolin
Last active August 2, 2022 14:50
Show Gist options
  • Save radiocolin/85c8c95a90e268b004d6acf73a90d00b to your computer and use it in GitHub Desktop.
Save radiocolin/85c8c95a90e268b004d6acf73a90d00b to your computer and use it in GitHub Desktop.
Auto-rotating OAuth Token in Python
#Blog post describing this pattern here: https://colinsent.me/The-Magical-Self-Rotating-Self-Getting-OAuth-Token-aa8e8a840e9643fd9f4ca8f9e97e53e9
import requests
import datetime
class MagicToken:
config = {
"client_id": "123456",
"client_secret": "shh",
"scope": [ "read", "write", "etc" ],
"auth_endpoint": "https://api.my-great-app.com/v1.0/auth"
}
def __init__(self):
self.__acquire_token()
def __acquire_token(self):
payload = {
"client_id" : config['client_id'],
"client_secret" : config['client_secret'],
"scope" : config['scope']
}
url = config['auth_endpoint']
response = requests.post(url, data=payload)
self.__access_token = result['access_token']
self.__token_expires = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(seconds=result['expiration'])
return
@property
def token(self):
if self.__token_expires > datetime.datetime.now(datetime.timezone.utc):
return self.__access_token
else:
self.__acquire_token()
return self.__access_token
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment