Authenticating Google Cloud Speech via GRPC on Android using an API key

假如想象 提交于 2019-12-10 15:33:58

问题


I've managed to get Google Cloud Speech working for my Android app using a service account in streaming mode via GRPC. However, according to what I've read, I shouldn't deploy an Android app with these credentials in them (currently stored as a JSON file in a resource) for security reasons. The correct thing is to create an API key, as described here: https://cloud.google.com/speech/docs/common/auth

This allows me to restrict access to my specific Android app. However, I have been unable to find out how to use the API Key from GRPC. I'm currently creating a GoogleCredentials instance from the JSON file, and this works fine. How can I get a credentials object from the API Key?


回答1:


you can try this with the API key

Metadata.Key<String> API_KEY = Metadata.Key.of("x-goog-api-key", Metadata.ASCII_STRING_MARSHALLER);

Metadata apiKeyMetadata = new Metadata();
apiKeyMetadata.put(API_KEY, yourApiKey);

final ManagedChannel channel = new OkHttpChannelProvider()
    .builderForAddress(HOSTNAME, PORT)
    .nameResolverFactory(new DnsNameResolverProvider())
    .intercept(MetadataUtils.newAttachHeadersInterceptor(apiKeyMetadata))
    .build();
speechStub = SpeechGrpc.newStub(channel);



回答2:


I cannot find any Android example. However, the sample iOS client sets up a gRPC connection using the API key. It puts the key in the request header. You can try translating the iOS code into Android.

https://github.com/GoogleCloudPlatform/ios-docs-samples/blob/master/speech/Objective-C/Speech-gRPC-Streaming/Speech/SpeechRecognitionService.m#L59




回答3:


Once you have the access token, you can use this method:

        final GoogleCredentials googleCredentials = new GoogleCredentials(accessToken) {
            @Override
            public AccessToken refreshAccessToken() throws IOException {
                return accessToken;
            }
        }.createScoped(OAUTH2_SCOPES);

You need to override the refreshAccessToken() as it's currently not supported.



来源:https://stackoverflow.com/questions/40060656/authenticating-google-cloud-speech-via-grpc-on-android-using-an-api-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!