微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用API​​密钥在Android上通过GRPC验证Google Cloud Speech

我已经设法通过GRPC使用流媒体模式的服务帐户为我的 Android应用程序运行Google Cloud Speech.但是,根据我所读到的内容,出于安全原因,我不应该在其中部署具有这些凭据的Android应用程序(当前存储为资源中的JSON文件).正确的是创建一个API密钥,如下所述: https://cloud.google.com/speech/docs/common/auth

这允许我限制对我的特定Android应用的访问.但是,我一直无法找到如何使用GRPC的API密钥.我目前正在从JSON文件创建一个GoogleCredentials实例,这很好用.如何从API密钥获取凭证对象?

解决方法

您可以使用API​​密钥尝试此操作

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

private static final class Interceptor implements ClientInterceptor {
  private final String apiKey;
  private static Metadata.Key<String> API_KEY_HEADER =
      Metadata.Key.of("x-goog-api-key",Metadata.ASCII_STRING_MARSHALLER);
  public Interceptor(String apiKey) {
    this.apiKey = apiKey;
  }
  @Override
  public <ReqT,RespT> ClientCall<ReqT,RespT> interceptCall(
      MethodDescriptor<ReqT,RespT> method,CallOptions callOptions,Channel next) {
    ClientCall<ReqT,RespT> call = next.newCall(method,callOptions);
    call = new ForwardingClientCall.SimpleForwardingClientCall<ReqT,RespT>(call) {
      @Override
      public void start(Listener<RespT> responseListener,Metadata headers) {
        if (apiKey != null && !apiKey.isEmpty()) {
          headers.put(API_KEY_HEADER,apiKey);
        }
        super.start(responseListener,headers);
      }
    };
    return call;
  }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐