如何将动态Google Cloud API密钥从服务器传递到客户端?

问题描述

当前,我正在测试Google Cloud的Speech API,并且想知道如何将动态Google Cloud API密钥从服务器传递给客户端应用。

语音功能将在客户端的应用程序上(React Native)。在考虑到对Google Cloud API或会话的每个请求之前,我正在考虑从服务器端(Nodejs)动态生成API密钥,并且寿命很短,然后传递给客户端。只有这样,客户才能使用Google服务。

主要担心的是,我不想将Google Cloud API密钥嵌入客户端应用程序,并且希望控制哪些客户端可以/不能使用该服务。有没有一种方法可以在服务器端以短生命周期动态生成API密钥并传递给客户端?谢谢。

更新:

我正在检查https://github.com/GoogleCloudPlatform/android-docs-samples/tree/master/speech/Speech并发现了建议:

This Android app uses JSON credential file locally stored in the resources. You should not do this in your production app. Instead,you should set up your own backend server that authenticates app users. The server should delegate API calls from your client app. This way,you can enforce usage quota per user. Alternatively,you should get the access token on the server side,and supply client app with it. The access token will expire in a short while.

这正是我想要做的,但是有人可以建议我如何实现这一目标吗?谢谢。

enter image description here

我正在尝试找出如何在服务器后端获取步骤2的API密钥。

解决方法

请不要将凭据存储在用户的浏览器中,幸运的是,您一直在尝试遵循这一原则!

此处可能有用的设置包含以下组件:

  • 通过身份提供程序在客户端应用程序中使用身份验证机制。您可以使用Okta,Auth0,Cognito或任何其他支持Oauth2的身份验证提供程序。
  • 使用相同的身份验证提供程序来保护自定义构建端点,该端点可以是Google Cloud Function。可以将其与Cloud Endpoints结合使用,但不一定。
  • 在同一个Cloud Function中,在检查了用户的身份之后,您可以调用语音API。
  • API密钥可以作为秘密存储在Google Secret Manager中。
  • Cloud Function充当API的“服务舱口”,将用户的来回请求传递给Google Cloud Speech API。

您的API密钥保留在后端,作为秘密存储。未使用身份验证提供程序进行身份验证的用户将永远无法访问Speech API。

Cloud speech API