如何在不将client_secret.json签入版本控制的情况下使用Google API?

时间:2018-07-30 20:35:15

标签: python google-api google-oauth google-sheets-api oauth2client

根据https://12factor.net/config,我正在一个项目中,我们的代码中没有凭证,而环境变量中则没有凭证。

我正在研究使用Google Sheets API整理数据库中的某些数据并将其放入Google表格中。这是https://developers.google.com/sheets/api/quickstart/python中的部分示例脚本:

from __future__ import print_function
from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file as oauth_file, client, tools

# Setup the Sheets API
SCOPES = 'https://www.googleapis.com/auth/spreadsheets.readonly'
store = oauth_file.Storage('token.json')
creds = store.get()
if not creds or creds.invalid:
    flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
    creds = tools.run_flow(flow, store)
service = build('sheets', 'v4', http=creds.authorize(Http()))

首先,在文档中我不清楚在这个示例中'token.json''credentials.json'应该是什么。从API控制台的“凭据”选项卡中,我下载了一个client_secret_<long suffix>.json,如下所示:

{"installed":{"client_id":"[our_client_id]","project_id":"nps-survey-1532981793379","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://accounts.google.com/o/oauth2/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"[our_client_secret]","redirect_uris":["urn:ietf:wg:oauth:2.0:oob","http://localhost"]}}

在此示例中,此JSON文件应为'token.json'还是'credentials.json'?另外,是否有一种方法可以通过直接指定客户端密钥和客户端ID,而不使用此JSON文件来实例化有效的creds

1 个答案:

答案 0 :(得分:0)

我最终使用了google_auth_oauthlib来完成针对Web应用程序(而非已安装的应用程序)的OAuth 2.0设置。 Flow对象有一个类方法from_client_config(),可以像这样使用(参见https://developers.google.com/identity/protocols/OAuth2WebServer):

from django.conf import settings
from django.shortcuts import redirect
import google.oauth2.credentials
import google_auth_oauthlib.flow


# Client configuration for an OAuth 2.0 web server application
# (cf. https://developers.google.com/identity/protocols/OAuth2WebServer)
CLIENT_CONFIG = {'web': {
    'client_id': settings.GOOGLE_CLIENT_ID,
    'project_id': settings.GOOGLE_PROJECT_ID,
    'auth_uri': 'https://accounts.google.com/o/oauth2/auth',
    'token_uri': 'https://www.googleapis.com/oauth2/v3/token',
    'auth_provider_x509_cert_url': 'https://www.googleapis.com/oauth2/v1/certs',
    'client_secret': settings.GOOGLE_CLIENT_SECRET,
    'redirect_uris': settings.GOOGLE_REDIRECT_URIS,
    'javascript_origins': settings.GOOGLE_JAVASCRIPT_ORIGINS}}

# This scope will allow the application to manage your calendars
SCOPES = ['https://www.googleapis.com/auth/calendar']



def get_authorization_url():
    # Use the information in the client_secret.json to identify
    # the application requesting authorization.
    flow = google_auth_oauthlib.flow.Flow.from_client_config(
        client_config=CLIENT_CONFIG,
        scopes=SCOPES)

    # Indicate where the API server will redirect the user after the user completes
    # the authorization flow. The redirect URI is required.
    flow.redirect_uri = 'http://localhost:8000'

    # Generate URL for request to Google's OAuth 2.0 server.
    # Use kwargs to set optional request parameters.
    authorization_url, state = flow.authorization_url(
        # Enable offline access so that you can refresh an access token without
        # re-prompting the user for permission. Recommended for web server apps.
        access_type='offline',
        # Enable incremental authorization. Recommended as a best practice.
        include_granted_scopes='true')

    return authorization_url, state

依次通过为每个相应属性调用settings来生成os.getenv()属性。这样,可以从环境变量而不是本地文件中获取配置。