Authenticate for using client libraries Stay organized with collections Save and categorize content based on your preferences.
This page describes how you can use client libraries to access Google APIs.
Client libraries make it easier to accessGoogle Cloud APIsusing a supported language. You can use Google Cloud APIs directly bymaking raw requests to the server, but client libraries provide simplificationsthat significantly reduce the amount of code you need to write. This isespecially true for authentication, because the client libraries supportApplication Default Credentials (ADC).
If you accept credential configurations (JSON, files, or streams) from anexternal source (for example, a customer), review thesecurity requirements when using credential configurations from an external source.
Use Application Default Credentials with client libraries
To use Application Default Credentials to authenticate your application, you must firstset up ADC for the environment where your application is running. When you use the client library to create a client, the client library automatically checks for and uses the credentials you have provided to ADC to authenticate to the APIs your code uses. Your application does not need to explicitly authenticate or manage tokens; these requirements are managed automatically by the authentication libraries.
For a local development environment, you can set up ADCwith your user credentials orwith service account impersonationby using the gcloud CLI. For production environments,you set up ADC byattaching a service account.
Example client creation
The following code samples create a client for the Cloud Storage service.Your code is likely to need different clients; these samples are meant only toshow how you can create a client and use it without any code to explicitlyauthenticate.
Before you can run the following samples, you must complete the following steps:
Go
import("context""fmt""io""cloud.google.com/go/storage""google.golang.org/api/iterator")// authenticateImplicitWithAdc uses Application Default Credentials// to automatically find credentials and authenticate.funcauthenticateImplicitWithAdc(wio.Writer,projectIdstring)error{// projectId := "your_project_id"ctx:=context.Background()// NOTE: Replace the client created below with the client required for your application.// Note that the credentials are not specified when constructing the client.// The client library finds your credentials using ADC.client,err:=storage.NewClient(ctx)iferr!=nil{returnfmt.Errorf("NewClient: %w",err)}deferclient.Close()it:=client.Buckets(ctx,projectId)for{bucketAttrs,err:=it.Next()iferr==iterator.Done{break}iferr!=nil{returnerr}fmt.Fprintf(w,"Bucket: %v\n",bucketAttrs.Name)}fmt.Fprintf(w,"Listed all storage buckets.\n")returnnil}Java
importcom.google.api.gax.paging.Page;importcom.google.cloud.storage.Bucket;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageOptions;importjava.io.IOException;publicclassAuthenticateImplicitWithAdc{publicstaticvoidmain(String[]args)throwsIOException{// TODO(Developer):// 1. Before running this sample,// set up Application Default Credentials as described in// https://cloud.google.com/docs/authentication/external/set-up-adc// 2. Replace the project variable below.// 3. Make sure you have the necessary permission to list storage buckets// "storage.buckets.list"StringprojectId="your-google-cloud-project-id";authenticateImplicitWithAdc(projectId);}// When interacting with Google Cloud Client libraries, the library can auto-detect the// credentials to use.publicstaticvoidauthenticateImplicitWithAdc(Stringproject)throwsIOException{// *NOTE*: Replace the client created below with the client required for your application.// Note that the credentials are not specified when constructing the client.// Hence, the client library will look for credentials using ADC.//// Initialize client that will be used to send requests. This client only needs to be created// once, and can be reused for multiple requests.Storagestorage=StorageOptions.newBuilder().setProjectId(project).build().getService();System.out.println("Buckets:");Page<Bucket>buckets=storage.list();for(Bucketbucket:buckets.iterateAll()){System.out.println(bucket.toString());}System.out.println("Listed all storage buckets.");}}Node.js
/** * TODO(developer): * 1. Uncomment and replace these variables before running the sample. * 2. Set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc * 3. Make sure you have the necessary permission to list storage buckets "storage.buckets.list" * (https://cloud.google.com/storage/docs/access-control/iam-permissions#bucket_permissions) */// const projectId = 'YOUR_PROJECT_ID';const{Storage}=require('@google-cloud/storage');asyncfunctionauthenticateImplicitWithAdc(){// This snippet demonstrates how to list buckets.// NOTE: Replace the client created below with the client required for your application.// Note that the credentials are not specified when constructing the client.// The client library finds your credentials using ADC.conststorage=newStorage({projectId,});const[buckets]=awaitstorage.getBuckets();console.log('Buckets:');for(constbucketofbuckets){console.log(`-${bucket.name}`);}console.log('Listed all storage buckets.');}authenticateImplicitWithAdc();PHP
// Imports the Cloud Storage client library.use Google\Cloud\Storage\StorageClient;/** * Authenticate to a cloud client library using a service account implicitly. * * @param string $projectId The Google project ID. */function auth_cloud_implicit($projectId){ $config = [ 'projectId' => $projectId, ]; # If you don't specify credentials when constructing the client, the # client library will look for credentials in the environment. $storage = new StorageClient($config); # Make an authenticated API request (listing storage buckets) foreach ($storage->buckets() as $bucket) { printf('Bucket: %s' . PHP_EOL, $bucket->name()); }}Python
fromgoogle.cloudimportstoragedefauthenticate_implicit_with_adc(project_id="your-google-cloud-project-id"):""" When interacting with Google Cloud Client libraries, the library can auto-detect the credentials to use. // TODO(Developer): // 1. Before running this sample, // set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc // 2. Replace the project variable. // 3. Make sure that the user account or service account that you are using // has the required permissions. For this sample, you must have "storage.buckets.list". Args: project_id: The project id of your Google Cloud project. """# This snippet demonstrates how to list buckets.# *NOTE*: Replace the client created below with the client required for your application.# Note that the credentials are not specified when constructing the client.# Hence, the client library will look for credentials using ADC.storage_client=storage.Client(project=project_id)buckets=storage_client.list_buckets()print("Buckets:")forbucketinbuckets:print(bucket.name)print("Listed all storage buckets.")Ruby
defauthenticate_implicit_with_adcproject_id:# The ID of your Google Cloud project# project_id = "your-google-cloud-project-id"#### When interacting with Google Cloud Client libraries, the library can auto-detect the# credentials to use.# TODO(Developer):# 1. Before running this sample,# set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc# 2. Replace the project variable.# 3. Make sure that the user account or service account that you are using# has the required permissions. For this sample, you must have "storage.buckets.list".###require"google/cloud/storage"# This sample demonstrates how to list buckets.# *NOTE*: Replace the client created below with the client required for your application.# Note that the credentials are not specified when constructing the client.# Hence, the client library will look for credentials using ADC.storage=Google::Cloud::Storage.newproject_id:project_idbuckets=storage.bucketsputs"Buckets: "buckets.eachdo|bucket|putsbucket.nameendputs"Plaintext: Listed all storage buckets."endUse API keys with client libraries
You can use an API keys only with client libraries for APIs that accept APIkeys. In addition, the API key must not have an API restriction that prevents itfrom being used for the API.
For more information about API keys created in express mode, see theGoogle Cloud express mode FAQ.
This example uses the Cloud Natural Language API, which accepts API keys, to demonstrate how you would provide an API key to the library.
C#
To run this sample, you must install theNatural Language client library.
usingGoogle.Cloud.Language.V1;usingSystem;publicclassUseApiKeySample{publicvoidAnalyzeSentiment(stringapiKey){LanguageServiceClientclient=newLanguageServiceClientBuilder{ApiKey=apiKey}.Build();stringtext="Hello, world!";AnalyzeSentimentResponseresponse=client.AnalyzeSentiment(Document.FromPlainText(text));Console.WriteLine($"Text: {text}");Sentimentsentiment=response.DocumentSentiment;Console.WriteLine($"Sentiment: {sentiment.Score}, {sentiment.Magnitude}");Console.WriteLine("Successfully authenticated using the API key");}}C++
To run this sample, you must install theNatural Language client library.
#include"google/cloud/language/v1/language_client.h"#include"google/cloud/credentials.h"#include"google/cloud/options.h"voidAuthenticateWithApiKey(std::vector<std::string>const&argv){if(argv.size()!=2){throwgoogle::cloud::testing_util::Usage{"authenticate-with-api-key <project-id> <api-key>"};}namespacegc=::google::cloud;autooptions=gc::Options{}.set<gc::UnifiedCredentialsOption>(gc::MakeApiKeyCredentials(argv[1]));autoclient=gc::language_v1::LanguageServiceClient(gc::language_v1::MakeLanguageServiceConnection(options));autoconstexprkText="Hello, world!";google::cloud::language::v1::Documentd;d.set_content(kText);d.set_type(google::cloud::language::v1::Document::PLAIN_TEXT);autoresponse=client.AnalyzeSentiment(d,{});if(!response)throwstd::move(response.status());autoconst&sentiment=response->document_sentiment();std::cout <<"Text: " <<kText <<"\n";std::cout <<"Sentiment: " <<sentiment.score() <<", " <<sentiment.magnitude() <<"\n";std::cout <<"Successfully authenticated using the API key\n";}Go
To run this sample, you must install theNatural Language client library.
import("context""fmt""io"language"cloud.google.com/go/language/apiv1""cloud.google.com/go/language/apiv1/languagepb""google.golang.org/api/option")// authenticateWithAPIKey authenticates with an API key for Google Language// service.funcauthenticateWithAPIKey(wio.Writer,apiKeystring)error{// apiKey := "api-key-string"ctx:=context.Background()// Initialize the Language Service client and set the API key.client,err:=language.NewClient(ctx,option.WithAPIKey(apiKey))iferr!=nil{returnfmt.Errorf("NewClient: %w",err)}deferclient.Close()text:="Hello, world!"// Make a request to analyze the sentiment of the text.res,err:=client.AnalyzeSentiment(ctx,&languagepb.AnalyzeSentimentRequest{Document:&languagepb.Document{Source:&languagepb.Document_Content{Content:text,},Type:languagepb.Document_PLAIN_TEXT,},})iferr!=nil{returnfmt.Errorf("AnalyzeSentiment: %w",err)}fmt.Fprintf(w,"Text: %s\n",text)fmt.Fprintf(w,"Sentiment score: %v\n",res.DocumentSentiment.Score)fmt.Fprintln(w,"Successfully authenticated using the API key.")returnnil}Node.js
To run this sample, you must install theNatural Language client library.
const{v1:{LanguageServiceClient},}=require('@google-cloud/language');/** * Authenticates with an API key for Google Language service. * * @param {string} apiKey An API Key to use */asyncfunctionauthenticateWithAPIKey(apiKey){constlanguage=newLanguageServiceClient({apiKey});// Alternatively:// const {GoogleAuth} = require('google-auth-library');// const auth = new GoogleAuth({apiKey});// const language = new LanguageServiceClient({auth});consttext='Hello, world!';const[response]=awaitlanguage.analyzeSentiment({document:{content:text,type:'PLAIN_TEXT',},});console.log(`Text:${text}`);console.log(`Sentiment:${response.documentSentiment.score},${response.documentSentiment.magnitude}`,);console.log('Successfully authenticated using the API key');}authenticateWithAPIKey();Python
To run this sample, you must install theNatural Language client library.
fromgoogle.cloudimportlanguage_v1defauthenticate_with_api_key(api_key_string:str)->None:""" Authenticates with an API key for Google Language service. TODO(Developer): Replace this variable before running the sample. Args: api_key_string: The API key to authenticate to the service. """# Initialize the Language Service client and set the API keyclient=language_v1.LanguageServiceClient(client_options={"api_key":api_key_string})text="Hello, world!"document=language_v1.Document(content=text,type_=language_v1.Document.Type.PLAIN_TEXT)# Make a request to analyze the sentiment of the text.sentiment=client.analyze_sentiment(request={"document":document}).document_sentimentprint(f"Text:{text}")print(f"Sentiment:{sentiment.score},{sentiment.magnitude}")print("Successfully authenticated using the API key")Ruby
To run this sample, you must install theNatural Language client library.
require"googleauth"require"google/cloud/language/v1"defauthenticate_with_api_keyapi_key_string# Authenticates with an API key for Google Language service.## TODO(Developer): Uncomment the following line and set the value before running this sample.## api_key_string = "mykey12345"## Note: You can also set the API key via environment variable:# export GOOGLE_API_KEY=your-api-key# and use Google::Auth::APIKeyCredentials.from_env method to load it.# Example:# credentials = Google::Auth::APIKeyCredentials.from_env# if credentials.nil?# puts "No API key found in environment"# exit# end# Initialize API key credentials using the class factory methodcredentials=Google::Auth::APIKeyCredentials.make_credsapi_key:api_key_string# Initialize the Language Service client with the API key credentialsclient=Google::Cloud::Language::V1::LanguageService::Client.newdo|config|config.credentials=credentialsend# Create a document to analyzetext="Hello, world!"document={content:text,type::PLAIN_TEXT}# Make a request to analyze the sentiment of the textsentiment=client.analyze_sentiment(document:document).document_sentimentputs"Text:#{text}"puts"Sentiment:#{sentiment.score},#{sentiment.magnitude}"puts"Successfully authenticated using the API key"endWhen you use API keys in your applications, ensure that they are kept secureduring both storage and transmission. Publicly exposing your API keys canlead to unexpected charges on your account. For more information, seeBest practices for managing API keys.
Security requirements when using credential configurations from an external source
Typically, you generate credential configurations by using gcloud CLIcommands or by using the Google Cloud console. For example, you can use thegcloud CLI to generate a local ADC file or a login configurationfile. Similarly, you can use the Google Cloud console to create and downloada service account key.
For some use cases, however, credential configurations are provided to you by anexternal entity; these credential configurations are intended to be used toauthenticate to Google APIs.
Some types of credential configurations include endpoints and file paths, whichthe authentication libraries use to acquire a token. When you accept credentialconfigurations from an external source, you must validate the configurationbefore using it. If you don't validate the configuration, a malicious actorcould use the credential to compromise your systems and data.
Validate credential configurations from external sources
How you need to validate your external credentials depends on what types ofcredential your application accepts.
Validate service account keys
If your application acceptsonly service account keys, use a credentialloader specific to service account keys, as shown in the following examples. Thetype-specific credential loader parses only the fields present for serviceaccount keys, which don't expose any vulnerabilities.
C#
varsaCredential=CredentialFactory.FromStream<ServiceAccountCredential>(stream);C++
autocred=google::cloud::MakeServiceAccountCredentials(json)Java
ServiceAccountCredentialscredentials=ServiceAccountCredentials.fromStream(credentialsStream);Node.js
constkeys=JSON.parse(json_input)constauthClient=JWT.fromJSON(keys);PHP
$cred = new Google\Auth\Credentials\ServiceAccountCredentials($scope, $jsonKey);Python
cred=service_account.Credentials.from_service_account_info(json_data)Ruby
creds=Google::Auth::ServiceAccountCredentials.make_creds(json_key_io:json_stream)If you can't use a type-specific credential loader, validate the credential byconfirming that the value for thetype field isservice_account. If thevalue for thetype field is any other value, don't use the service accountkey.
Validate other credential configurations
If your application acceptsany type of credential besides a service accountkey, you must perform additional verification. Examples of other types ofcredential configurations includeADC credential files,Workload Identity Federation credential files,orWorkforce Identity Federation login configuration files.
The following table lists the fields you need to validate, if they are presentin your credentials. Not all of these fields are present for all credentialconfigurations.
Important: If any of these fields contain a value that does not conform to theexpected value, don't use the credential.| Field | Purpose | Expected value |
|---|---|---|
service_account_impersonation_url | The authentication libraries use this field to access an endpoint to generate an access token for the service account being impersonated. | https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/service account email:generateAccessToken |
token_url | The authentication libraries send an external token to this endpoint to exchange it for afederated access token. | https://sts.googleapis.com/v1/token |
credential_source.file | The authentication libraries read an external token from the file at the location specified by this field and send it to thetoken_url endpoint. | The path for a file containing an external token. You should recognize this path. |
credential_source.url | An endpoint that returns an external token. The authentication libraries send a request to this URL and send the response to thetoken_url endpoint. | One of the following items:
|
credential_source.executable.command | If theGOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment variable is set to1, the authentication libraries run this command or executable file. | An executable file or command that returns an external token. You should recognize this command and validate that it is safe. |
credential_source.aws.url | The authentication libraries issue a request to this URL to retrieve an AWS security token. | Either one of these exact values:
|
credential_source.aws.region_url | The authentication libraries issue a request to this URL to retrieve the active AWS region. | Either one of these exact values:
|
credential_source.aws.imdsv2_session_token_url | The authentication libraries issue a request to this URL to retrieve the AWS session token. | Either one of these exact values:
|
What's next
- Learn more aboutApplication Default Credentials.
- Learn more aboutAPI keys.
- See an overview ofAuthentication methods.
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-12-15 UTC.