如何在 android 应用程序中从服务器安全地获取凭据?

How to fetch a credential securely from a server in android app?

我正在尝试在我的 Android 应用程序中使用 Google Cloud Speech-to-Text API 库。在 Kotlin here.

上有一个来自 Google 的客户端代码示例

它有一个代码片段:

        // NOTE: The line below uses an embedded credential (res / raw / sa.json).
        // You should not package a credential with real application.
        // Instead, you should get a credential securely from a server.
        context? .resources? .openRawResource (R.raw.credential).use {
            SpeechClient.create (
                SpeechSettings.newBuilder ()
                    .setCredentialsProvider {GoogleCredentials.fromStream (it)}
                    .build ())
        }

我的应用程序有一个后端服务器。 "get a credential securely from a server"实际上如何?有例子吗?

John 提供的 link 应该会给您一些见解,因为它检查了如何识别对 Web 服务器应用程序使用 OAuth。

更符合你实际情况的可以参考OAuth 2.0 for Mobile & Desktop Apps, more precisely at AppAuth for Android library. You can follow this codelab官方文档中的建议。

编辑:如果以上没有用,我想您对 Setting Up Authentication for Server to Server Production Applications.

更感兴趣

如果客户端将使用您的凭据,那么我将修改代码,以便所有 API 调用都从后端服务器进行,​​并且客户端向服务器发送必要的信息以进行调用.然后,为了进行身份验证,我将使用 this 之后的服务帐户。

注意文档末尾描述的best practices

我找到了问题的答案here

Set Up to Authenticate With Your Project's Credentials 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.