I have a desktop application written in tkinter with Python.
This desktop application does a number of things, including uploading files to google storage buckets.
This application should have an uptime of many days, and ideally allow to be re-started without having to re-login once authenticated.
I have a “device” oauth login flow that works fine — it gives me a refresh token, and an auth token.
I save these parameters locally, in a resonably secure fashion because refresh tokens are legit credentials. (Although if they’re stolen, at least the next refresh will discover this, and perhaps be able to do something about it.)
The auth token works, for an hour. Then it needs refreshing.
Here is where the documentation just hasn’t helped me. How do I properly refresh the credentials I have, in a way that both:
- The google storage client sees the updated authtoken for future requests.
- The code calling refresh sees the newly exchanged refresh token, such that I can save it locally so the next application start will still work.
I can have the google storage Client auto-refresh the credentials. However, when it does that, I can’t find a way of getting the refresh token back out for persistent storage, so the next start of the application will still work.
I also can’t find a good way to know when this refresh happens, so that I can know to store the token appropriately.
Obligatory code:
from google.cloud import storage
from google.oauth2 import credentials
import oa
...
def make_client_from_token(token):
creds = credentials.Credentials(token['access_token'],
refresh_token=token['refresh_token'],
token_uri=oa.token_url,
client_id=oa.CLIENT_ID,
client_secret=oa.CLIENT_SECRET)
return storage.Client(credentials=creds, project=PROJECT)
I am assuming that the refresh token is invalidated and replaced with a new token when used, which seems to match the behavior I see, but if this is a bad assumption, I’d like to know, too!
So, what am I missing?