Jacob Kaplan-Moss

Today I Learned…

Stop storing credentials in plaintext part #624: gspread edition

Here’s how to safely store and use credentials for the Python gspread library, a Python API for Google Sheets.

Background: How To Keep A Secret, by Glyph The most relevant parts start around 15:00, but watch the whole thing, it’s great and worth your time.

Pre-requisites

Install keyring: pip install keyring or equivalent.

Storing credentials

Create service account credentials as explained in the gspread docs. This ends with you having a JSON credentials file on your disk somewhere (unacceptable).

Import the installed credentials into your keychain:

python -m keyring set gspread credentials < path/to/credentials.json

gspread and credentials are arbitrary values here – they’re a “service” and “username” value, but they can be whatever. They’re not secret values.

You can verify that you’ve done it correctly by running:

python -m keyring get gspread credentials

Now delete that credentials file.

Reading credentials and authorizing gspread

Hard part done, now you just need to auth the gspread library against the creds stored in your keychain. The key is using the (undocumented 🙁) service_account_from_dict method:

import json
import keyring
import gspread

credentials = keyring.get_password("gspread", "credentials")
client = gspread.service_account_from_dict(json.loads(credentials))

Those arguments (gspread and credentials) are the same service/username values you provided above.

Now you can use that client object as documented in the gspread docs. Congratulations, one less poor security practice!