如何在Heroku上使用Google API凭据json? [英] How to use Google API credentials json on Heroku?
问题描述
我正在使用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变量,并使用oauth2client
的from_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-构建包将自动生成google-credentials.json并将其填充为Google凭据内容.
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屋!