Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 712
daoudc Avatar asked Jan 05 '23 05:01

daoudc


2 Answers

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);
like image 140
Jeongho Ahn Avatar answered Feb 06 '23 11:02

Jeongho Ahn


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

like image 40
Cheuksan Edward Wang Avatar answered Feb 06 '23 11:02

Cheuksan Edward Wang