As bibliotecas de cliente do Cloud para Java usam a
biblioteca de autenticação do Google para Java
para autenticar solicitações. Essa biblioteca oferece suporte a vários tipos de autenticação.
Para mais detalhes, consulte o README.md
e o javadoc do projeto.
Autenticação em um Cloud de Confiance by S3NS ambiente
Ao usar Cloud de Confiance by S3NS bibliotecas de um Cloud de Confiance by S3NS ambiente (como o Compute Engine, o Google Kubernetes Engine ou o App Engine), não é necessário realizar etapas de autenticação adicionais.
Um exemplo de chamada sem autenticação adicional:
Storage storage = StorageOptions.getDefaultInstance().getService();
Autenticação em ambientes não-Cloud de Confiance by S3NS
Para autenticar em um ambiente não-Cloud de Confiance by S3NS há três opções comuns:
- (Recomendado) Use uma conta de serviço.
- Use o SDK Google Cloud com um ambiente de teste local.
- Use um token de acesso OAuth2.
Usar uma conta de serviço
Depois de fazer o download da chave, faça uma destas ações:
- Defina a variável de ambiente
GOOGLE_APPLICATION_CREDENTIALScomo o local da chave. Exemplo:
export GOOGLE_APPLICATION_CREDENTIALS=/path/to/my/key.json- Forneça o arquivo de credenciais JSON ao criar as opções de serviço. Por exemplo, esse objeto
Storagetem as permissões necessárias para interagir com os dados do Cloud Storage:
Storage storage = StorageOptions.newBuilder() .setCredentials(ServiceAccountCredentials.fromStream(new FileInputStream("/path/to/my/key.json"))) .build() .getService();- Defina a variável de ambiente
Usar o SDK Google Cloud com um ambiente de teste local
Se você estiver usando um ambiente local para desenvolvimento ou teste, use o SDK Google Cloud.
Crie as credenciais padrão do aplicativo com gcloud auth application-default login. As bibliotecas de cliente do Cloud para Java vão detectar essas credenciais automaticamente.
Usar um token de acesso OAuth2
Se você tiver um token de acesso OAuth2, use-o para autenticar. Nesse caso, o token de acesso não será atualizado automaticamente:
Credentials credentials = GoogleCredentials.create(new AccessToken(accessToken, expirationTime));
Storage storage = StorageOptions.newBuilder()
.setCredentials(credentials)
.build()
.getService();
Vejamos outro exemplo:
Credentials credentials = GoogleCredentials.create(new AccessToken(accessToken, expirationTime));
CloudTasksSettings cloudTasksSettings = CloudTasksSettings.newBuilder()
.setCredentialProvider(FixedCredentialsProvider.create(credentials))
.build();
CloudTasksClient cloudTasksClient = CloudTasksClient.create(cloudTasksSettings);
Application Default Credentials
Se você não fornecer credenciais, as bibliotecas de cliente do Cloud para Java vão tentar detectá-las no ambiente usando GoogleCredentials.getApplicationDefault().
Esse método pesquisa as Application Default Credentials nos seguintes locais, em ordem:
- O arquivo de credenciais apontado pela variável de ambiente
GOOGLE_APPLICATION_CREDENTIALS. - Credenciais fornecidas pelo comando
gcloud auth application-default logindo SDK Google Cloud. - Credenciais integradas do Google App Engine.
- Cloud de Confiance by S3NS Credenciais integradas do shell.
- Credenciais de conta de serviço integradas do Google Compute Engine.
Autenticação com uma chave de API
Algumas Cloud de Confiance by S3NS APIs oferecem suporte à autenticação com chaves de API.
Para usar uma chave de API com as bibliotecas de cliente do Cloud para Java, defina manualmente o cabeçalho x-goog-api-key para o cliente de serviço relevante.
Por exemplo, para definir a chave de API com o
Language service:
public LanguageServiceClient createGrpcClientWithApiKey(String apiKey) throws Exception {
// Manually set the API key using the header
Map<String, String> header = new HashMap<String, String>() { {put("x-goog-api-key", apiKey);}};
FixedHeaderProvider headerProvider = FixedHeaderProvider.create(header);
// Create the client
TransportChannelProvider transportChannelProvider = InstantiatingGrpcChannelProvider.newBuilder().setHeaderProvider(headerProvider).build();
LanguageServiceSettings settings = LanguageServiceSettings.newBuilder().setTransportChannelProvider(transportChannelProvider).build();
LanguageServiceClient client = LanguageServiceClient.create(settings);
return client;
}
Um exemplo de instanciação com o cliente de linguagem usando REST:
public LanguageServiceClient createRestClientWithApiKey(String apiKey) throws Exception {
// Manually set the API key header
Map<String, String> header = new HashMap<String, String>() { {put("x-goog-api-key", apiKey);}};
FixedHeaderProvider headerProvider = FixedHeaderProvider.create(header);
// Create the client
TransportChannelProvider transportChannelProvider = InstantiatingHttpJsonChannelProvider.newBuilder().setHeaderProvider(headerProvider).build();
LanguageServiceSettings settings = LanguageServiceSettings.newBuilder().setTransportChannelProvider(transportChannelProvider).build();
LanguageServiceClient client = LanguageServiceClient.create(settings);
return client;
}