如何在 Heroku 上使用 Google API 凭据 json? [英] How to use Google API credentials json on Heroku?

查看:24
本文介绍了如何在 Heroku 上使用 Google API 凭据 json?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Google Calendar API 制作一个应用,并计划在 Heroku 上构建它.
我有关于身份验证的问题.通常我会为此使用凭证 json 文件,但这次出于安全原因我不想将它上传到 Heroku.
如何在 Heroku 上进行身份验证?

I'm making an app using Google Calendar API, and planning to build it on Heroku.
I have a problem about authentication. Usually I use credential json file for that, but this time I don't want to upload it on Heroku for security reason.
How can I make authentiation on Heroku?

现在,我将我的 json 放到一个 env 变量中,并使用 oauth2clientfrom_json 方法.

For now, I put my json to an env variable, and use oauth2client's from_json method.

def get_credentials():
    credentials_json = os.environ['GOOGLE_APPLICATION_CREDENTIALS']
    credentials = GoogleCredentials.from_json(credentials_json)
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else: # Needed only for compatibility with Python 2.6
            credentials = tools.run(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials 

但是这段代码并不完美.如果凭据无效,我希望代码将新凭据写入 env 变量,而不是写入新文件.
有没有更好的办法?

But this code isn't perfect. If the credentials is invalid, I want the code to write the new credentials to the env variable, not to a new file.
Is there any better way?

推荐答案

我花了一整天的时间来寻找解决方案,因为它很棘手.无论您使用何种语言,解决方案都是一样的.

I spent an entire day to find the solution because it's tricky. No matter your language, the solution will be the same.

1 - 在 Heroku 仪表板中声明您的环境变量,例如:

1 - Declare your env variables from in Heroku dashboard like :

GOOGLE_CREDENTIALS 变量是服务帐户凭据 JSON 文件的内容.字符串google-credentials.json"中的 GOOGLE_APPLICATION_CREDENTIALS 环境变量

The GOOGLE_CREDENTIALS variable is the content of service account credential JSON file as is. The GOOGLE_APPLICATION_CREDENTIALS env variable in the string "google-credentials.json"

2 - 声明变量后,从命令行添加 builpack:

2 - Once variables are declared, add the builpack from command line :

$ heroku buildpacks:add https://github.com/elishaterada/heroku-google-application-credentials-buildpack

3 - 推动.更新一个小东西并推送.

3 - Make a push. Update a tiny thing and push.

4 - buildpack 将自动生成一个 google-credentials.json 并用谷歌凭据内容的内容填充它.

4 - The buildpack will automatically generate a google-credentials.json and fill it with the content of the google credentials content.

如果你在某件事上失败了,那它就行不通了.使用 Heroku bash 检查 google-credentials.json 的内容.

If you failed at something, it will not work. Check the content of the google-credentials.json with the Heroku bash.

这篇关于如何在 Heroku 上使用 Google API 凭据 json?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆