Skip to content

Instantly share code, notes, and snippets.

@dev-drprasad
Created December 22, 2017 19:33
Show Gist options
  • Save dev-drprasad/b676e76946086d6acb40e834920fcd07 to your computer and use it in GitHub Desktop.
Save dev-drprasad/b676e76946086d6acb40e834920fcd07 to your computer and use it in GitHub Desktop.
OAuth Client to refresh access token with caching
import json
import requests
from time import time
class OAuthClient:
def __init__(self, server, client_id, client_secret, grant_type, scope):
self.server = server
self.client_id = client_id
self.client_secret = client_secret
self.grant_type = grant_type
self.scope = scope
self.expires_on = 0
self._access_token = None
def get_access_token(self):
if time() < self.expires_on:
print('returning cached token')
return self._access_token
body = {
'grant_type': self.grant_type,
'client_id': self.client_id,
'client_secret': self.client_secret,
'scope': self.scope,
}
response = requests.post(self.server, data=body)
response_json = json.loads(response.content.decode('utf8'))
access_token = response_json.get('access_token')
self._access_token = access_token
expires_in = response_json.get('expires_in')
self.expires_on = time() + expires_in
return access_token
if __name__ == '__main__':
body = { 'grant_type': 'client_credentials',
'client_id': '1234567890',
'client_secret': 'XXXXXXXXXXXXXX',
'scope': 'https://api.example.com/default',
'server': 'https://login.example.com/oauth2/v2.0/token',
}
client = OAuthClient(**body)
print(client.get_access_token())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment