paris_serviola paris_serviola -4 years ago 95
Python Question

Is it possible to store authentication token in a separate file?

I am building a command line tool using python that interfaces with an RESTful api. The API uses oauth2 for authentication. Rather than asking for access_token every time user runs the python tool. Can I store the access_token in some way so that I can use it till its lifespan? If it is then how safe it is.

Answer Source

You can store the access token in a file on your user's desktop.

You can do so using a storage. Assuming you use oauth2client:

# Reading credentials
store = oauth2client.file.Storage(cred_path)
credentials = store.get()

# Writing credentials
creds = client.AccessTokenCredentials(access_token, user_agent)
creds.access_token = access_token
creds.refresh_token = refresh_token
creds.client_id = client_id
creds.client_secret = client_secret

# For some reason it does not save all the credentials,
# so write them to a json file manually instead
with open(credential_path, "w") as f:
    f.write(creds.to_json)

In terms of security, I would not see much of a threat here as these access tokens will be on a user's desktop. If someone wants to get their access token, they would need to have read access to that file for that time frame. However, if they can already do that, they most likely also can use your script to send them a copy of the user's access token every time it is authenticated. But take my word lightly as I'm not a professional in that area. See information security stack exchange.

A post in information security stack exchange did talk about this:

these tokens give access to some fairly privileged information about your users.

However, the question was addressed to a database instead.

In conclusion, you can keep it in a file. (But take my word with a grain of salt)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download