IMG_20200908_114948.jpg

Blog

HOW TO: authorize google oauth credentials through a Heroku environment

You want to use Google APIs to access your personal Google data on a heroku dyno without having to re-auth. Here's how it works:

  1. Take a look at heroku-config and install it.
  2. Create a file called ".env" in your project root directory and fill it with your environment variables. Make sure there's no spaces between your assignments.
    Example

  3. Make sure everything is running smooth with "$ foreman start"

  4. Implement the "read_env()" function shown here

  5. Create an instance of OAuth2WebServerFlow with access_type="offline" and approval_prompt='force'. This will grant you a refresh token and relieve you of having to re-auth every time your application runs.

  6. Run your application with typical OAuth storage shown here and copy your stored credentials into your CREDENTIALS variable in your .env file.

  7. Load your credentials like so: json.loads(os.environ.get('CREDENTIALS'))

  8. Construct an OAuth2Credentials instance

  9. Now your refresh token should prevent you from having to authorize and your credentials should be valid. You can now authorize and make API requests.