我正在使用Google Calendar API开发应用程序,并计划在Heroku上构建它。
我有关于身份验证的问题。通常,我为此使用凭据json文件,但是出于安全原因,这一次我不想将其上传到Heroku。
如何在Heroku上进行身份验证?
现在,我将json放入一个env变量,并使用oauth2client的from_json方法。
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
Run Code Online (Sandbox Code Playgroud)
但是这段代码并不完美。如果凭据无效,我希望代码将新凭据写入env变量,而不是新文件。
有什么更好的办法吗?
对于 Google Cloud Platform 存储客户端的身份验证,我不想将服务帐户 JSON(您创建的凭据文件)写入磁盘。我想在从所有云实例共享的 Hashicorp Vault 密钥库加载它们后,将它们纯粹保留在内存中。有没有办法直接传递 JSON 凭据,而不是传递类似路径/文件对象?
我了解如何使用类似路径/文件对象来执行此操作,如下所示,但这是我想要避免的(由于安全问题,我宁愿永远不要将它们写入磁盘):
from google.cloud import storage
# set an environment variable that relies on a JSON file
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/service_account.json"
# create the client (assumes the environment variable is set)
client = storage.Client()
# alternately, one can create the client without the environment
# variable, but this still relies on a JSON file.
client = storage.Client.from_service_account_json("/path/to/service_account.json")
Run Code Online (Sandbox Code Playgroud)
我试图通过直接引用 JSON 数据 (json_data) 来解决这个问题,但这会引发错误:TypeError: expected str, bytes or os.PathLike object, not dict
json_data …Run Code Online (Sandbox Code Playgroud) 我可以从文件中执行以下操作:
from google.cloud import storage
self.client = storage.Client.from_service_account_json('/Users/david/file-163219.json')
Run Code Online (Sandbox Code Playgroud)
但是,如果我尝试直接传递凭据,则会收到错误消息:
credentials_dict = {
"type": "service_account",
"project_id": "asdf-163219",
"private_key_id": "asdf2938492837498234",
}
credentials = service_account.Credentials.from_service_account_info(credentials_dict)
self.client = storage.Client(credentials=credentials)
Run Code Online (Sandbox Code Playgroud)
但后来我收到一个错误:
google.auth.exceptions.DefaultCredentialsError:无法自动确定凭据。请设置 GOOGLE_APPLICATION_CREDENTIALS 或明确创建凭据并重新运行应用程序。有关更多信息,请参阅https://developers.google.com/accounts/docs/application-default-credentials。
传递凭据字典的正确方法是什么?