我正在构建一个使用Google Cloud Speech的应用。
我的应用中有一个Google服务帐户密钥,我用它来调用API。
当一个用户使用它时效果很好,但当多个用户同时使用它时不起作用。
例如,只有一个用户可用或全部不可用。
服务帐户密钥的权利是项目所有者。
我认为这是一个服务帐户关键问题...... 我该如何解决?
private class AccessTokenTask extends AsyncTask<Void, Void, AccessToken> {
@Override
protected AccessToken doInBackground(Void... voids) {
final SharedPreferences prefs = mContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE);
String tokenValue = prefs.getString(PREF_ACCESS_TOKEN_VALUE, null);
long expirationTime = prefs.getLong(PREF_ACCESS_TOKEN_EXPIRATION_TIME, -1);
// Check if the current token is still valid for a while
if (tokenValue != null && expirationTime > 0) {
if (expirationTime > System.currentTimeMillis() + ACCESS_TOKEN_EXPIRATION_TOLERANCE) {
return new AccessToken(tokenValue, new Date(expirationTime));
}
}
final InputStream stream = mContext.getResources().openRawResource(R.raw.credential);
try {
final GoogleCredentials credentials = GoogleCredentials.fromStream(stream).createScoped(SCOPE);
final AccessToken token = credentials.refreshAccessToken();
prefs.edit()
.putString(PREF_ACCESS_TOKEN_VALUE, token.getTokenValue())
.putLong(PREF_ACCESS_TOKEN_EXPIRATION_TIME, token.getExpirationTime().getTime())
.apply();
return token;
} catch (IOException e) {
Log.e(TAG, "Failed to obtain access token.", e);
}
return null;
}
@Override
protected void onPostExecute(AccessToken accessToken) {
mAccessTokenTask = null;
final ManagedChannel channel = new OkHttpChannelProvider()
.builderForAddress(GOOGLE_API_HOSTNAME, GOOGLE_API_PORT)
.nameResolverFactory(new DnsNameResolverProvider())
.intercept(new GoogleCredentialsInterceptor(new GoogleCredentials(accessToken)
.createScoped(SCOPE)))
.build();
mApi = SpeechGrpc.newStub(channel);
// Schedule access token refresh before it expires
if (mHandler != null) {
mHandler.postDelayed(mFetchAccessTokenRunnable,
Math.max(accessToken.getExpirationTime().getTime() - System.currentTimeMillis() - ACCESS_TOKEN_FETCH_MARGIN, ACCESS_TOKEN_EXPIRATION_TOLERANCE));
}
}
}
此代码是调用&#39; credential.json&#39;的代码。 Android上的文件并获取访问令牌&#39;。
此应用程序的服务器是python并通过http进行通信。
https://github.com/GoogleCloudPlatform/android-docs-samples/tree/master/speech/Speech
上面链接中的描述告诉您将身份验证委派给服务器。
我想用python代码编写那部分。 我该怎么办?
答案 0 :(得分:0)
在您在说明中提供的链接中,他们建议您先阅读basic authentication concepts document。在您的情况下,请使用Android应用程序的服务帐户。
我了解您已经能够provide end user credentials加入Google Cloud Platform API,例如Cloud Speech API。
如果要对应用程序的多个用户进行身份验证,则应使用Firebase authentication。该链接包含简要说明和教程。
您可以使用GCP several Python client libraries,具体取决于您要在服务器上执行的操作。关于服务器端的Python身份验证,this documentation显示了Google云端存储的身份验证的工作原理(将此示例作为参考)。