Search code examples
pythonoauthoauth-2.0google-oauthgoogle-sheets-api

How does user authentication work in the Google Sheets API with Python?


I am a fairly new developer. I have no OAuth2 experience and every time I try to read explanations of it I can't seem to figure out what it means in a practical sense.

Here's what I'm trying to accomplish. I'm writing an app in Python which I want to be able to read an arbitrary Google sheet and manipulate the data. I've followed Google's official guide here and set up the quickstart.py example. It works fine, and I've been able to extend it to do other things without any problem – having maintained the specific file setup created in the quickstart guide.

Now here's where I'm confused. Suppose I want someone else to be able to use my app with their own spreadsheets and Google account now. Isn't the client_secret.json file required for the app to work? But isn't it (as it's name would obviously suggest) supposed to be kept secret? They need to create their own credentials, right? But don't you need the client_secret.json file in order to create credentials in the first place? How does this all work?

What needs to be in place for someone to be able to run the Python script and get connected through their account to a spreadsheet from square one? I personally just don't understand how OAuth2 is supposed to be applied in this particular situation beyond my own Google account and the setup described in the guide.

Perhaps this question seems too wide ranging. If so, here's the bottom line: How do I take the Python quickstart example outlined at the link here and make it so anyone can just run the script on their computer and have it work? (guiding them through all needed setup like any normal application needing access to their Google account)


Solution

  • Perhaps some of the confusion stems from the word "client" in client_secret. The client is your application. Yes its details should be kept secret insofar as anybody with the client_secret can impersonate your app. Apart from being a nuisance, the impact of such impersonation is minimal in that it does not extend to Eve being able to access Alice's data.

    Each user of your app will need to go through the OAuth dance to give the app access to their data. This permission is manifested in a Refresh Token and Access Token, and it is these which each user needs to keep private.

    If you do distribute a client_secret, consider using a sacrificial (ie. fake) Google Account. That way, any abuse won't affect your primary Google Account.

    An alternative to consider would be to provide your users with instructions on how to register their own app on the dev console, and thus generate their own client_secret.