Python oauth flow, store_token doesnt seem to work
Hi,
I'm trying to implement oauth2 with Python and I cant wrap my mind around the store_token mechanism and how to automate the entire process. This is what I understand so far -
First I need to manually (i.e. not using python) navigate in browser to the auth_url which is provided by oauth.get_authorization_url() -
auth_url, csrf_token = oauth.get_authorization_url('http://127.0.0.1')
in auth_url, i'm going through the authorization and grant process and eventually I'm getting the code to be used with
access_token, refresh_token = oauth.authenticate(THE_CODE_THAT_I_GOT)
Again, this is done manually (placing oauth.authenticate() as watched variable in PyCharm I can see access and refresh tokens) and not programmatically - from what I understand, this is a one time process, am I right?
Now, with access_token and refresh_token at hand, I can store them, currently in a file and they should be replaced with the store_tokens callback during the initialization of a OAuth2 instance. is this right?.
This is where things are getting awkward as It looks like my store_token callback is simply not called so I'm pretty sure that I'm missing something...
I did notice that the store_tokens callback is called when I'm calling oauth.authenticate() but I'm not sure it should be called whenever the API is used but should be called only once.
This is my complete code -
class BoxIntegration(object):
def __init__(self):
self.tokens_loc = 'box_tokens.cfg'
self.access_token = ''
self.refresh_token = ''
self.get_access_tokens()
def read_tokens(self):
with open(self.tokens_loc, 'r') as box_tokens:
self.access_token = box_tokens.readline().rstrip('\n')
self.refresh_token = box_tokens.readline().rstrip('\n')
return self.access_token, self.refresh_token
def store_tokens(self, access_token, refresh_token):
with open(self.tokens_loc + '.tmp', 'w') as box_tokens:
box_tokens.write(access_token+'\n')
box_tokens.write(refresh_token)
os.remove(self.tokens_loc)
os.rename(self.tokens_loc + '.tmp', self.tokens_loc)
# Authenticate with Box API
def get_access_tokens(self):
parser = ConfigParser()
parser.read('keys.conf')
client_id = parser.get('box_keys', 'client_id')
client_secret = parser.get('box_keys', 'client_secret')
# Retrieve tokens from secure store
access_token, refresh_token = self.read_tokens()
# Set up authorisation using the tokens we've retrieved
oauth = OAuth2(
client_id=client_id,
client_secret=client_secret,
access_token=access_token,
refresh_token=refresh_token,
store_tokens=self.store_tokens,
)
return oauth
client = Client(BoxIntegration())
What am I missing?
Thanks!
サインインしてコメントを残してください。
コメント
0件のコメント