Getting Started with Authentication

This article shows the recommended way to authenticate to a Cloud API.

Authentication refers to the process of determining a client's identity. Authorization refers to the process of determining what permissions an authenticated client has for a set of resources. That is, authentication refers to who you are, and authorization refers to what you can do.

For authentication, we recommend using a service account: a Google account that is associated with your GCP project, as opposed to a specific user. Service accounts can be used for authentication regardless of where your code runs (locally, Compute Engine, App Engine, on premises, etc.). For more information about other authentication types, see authentication overview.

Creating a service account

GCP Console

  1. In Cloud Platform Console, navigate to the Create service account key page.

  2. From the Service account dropdown, select New service account.

    Create new service account

  3. Input a name into the Service account name form field.

  4. From the Role dropdown, select Project > Owner.

  5. Click the Create button. A JSON file that contains your key downloads to your computer.

Gcloud

You can run the following commands using the Google Cloud SDK on your local machine, or within Cloud Shell.

  1. Create the service account. Replace [NAME] with a service account name.

    gcloud iam service-accounts create [NAME]

  2. Grant permissions to the service account. Replace [NAME] with the service account name from the previous step, and [PROJECT_ID] with your project ID.

    gcloud projects add-iam-policy-binding [PROJECT_ID] \
      --member "serviceAccount:[NAME]@[PROJECT_ID].iam.gserviceaccount.com" \
      --role "roles/owner"`

  3. Generate the key file. The following command creates a file named service-account.json in your current working directory. Replace [NAME] with the service account name from the previous step, and [PROJECT_ID] with your project ID.

    gcloud iam service-accounts keys create service-account.json \
      --iam-account [NAME]@[PROJECT_ID].iam.gserviceaccount.com`

Using a service account in your application

Provide the credentials to your application code by setting the environment variable GOOGLE_APPLICATION_CREDENTIALS to point to the JSON file you downloaded in the previous step.

Linux or Mac OS X

export GOOGLE_APPLICATION_CREDENTIALS=<path_to_service_account_file>

Windows

set GOOGLE_APPLICATION_CREDENTIALS=<path_to_service_account_file>

After setting the environment variable, you don't need to explicitly specify your credentials in code when using a Google Cloud Client Library. The client library can determine your credentials implicitly, as shown in the following code example. For more information, see providing credentials to your application.

C#

public object AuthImplicit(string projectId)
{
    // If you don't specify credentials when constructing the client, the
    // client library will look for credentials in the environment.
    var storage = StorageClient.Create();
    // Make an authenticated API request.
    var buckets = storage.ListBuckets(projectId);
    foreach (var bucket in buckets)
    {
        Console.WriteLine(bucket.Name);
    }
    return null;
}

Go

// For API packages whose import path is starting with "cloud.google.com/go",
// such as cloud.google.com/go/storage in this case, if there are no credentials
// provided, the client library will look for credentials in the environment.
storageClient, err := storage.NewClient(ctx)
if err != nil {
	log.Fatal(err)
}

it := storageClient.Buckets(ctx, "project-id")
for {
	bucketAttrs, err := it.Next()
	if err == iterator.Done {
		break
	}
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(bucketAttrs.Name)
}

// For packages whose import path is starting with "google.golang.org/api",
// such as google.golang.org/api/cloudkms/v1, use the
// golang.org/x/oauth2/google package as shown below.
oauthClient, err := google.DefaultClient(ctx, cloudkms.CloudPlatformScope)
if err != nil {
	log.Fatal(err)
}

kmsService, err := cloudkms.New(oauthClient)
if err != nil {
	log.Fatal(err)
}

Java

// If you don't specify credentials when constructing the client, the
// client library will look for credentials in the environment.

Storage storage = StorageOptions.getDefaultInstance().getService();

Page<Bucket> buckets = storage.list();
for (Bucket bucket : buckets.iterateAll()) {
  // do something with the info
}

Node.js

// Imports the Google Cloud client library.
const Storage = require('@google-cloud/storage');

// Instantiates a client. If you don't specify credentials when constructing
// the client, the client library will look for credentials in the
// environment.
const storage = Storage();

// Makes an authenticated API request.
storage
  .getBuckets()
  .then((results) => {
    const buckets = results[0];

    console.log('Buckets:');
    buckets.forEach((bucket) => {
      console.log(bucket.name);
    });
  })
  .catch((err) => {
    console.error('ERROR:', err);
  });

PHP

namespace Google\Cloud\Samples\Auth;

// Imports the Google Cloud Storage client library.
use Google\Cloud\Storage\StorageClient;

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

def implicit():
    from google.cloud import storage

    # If you don't specify credentials when constructing the client, the
    # client library will look for credentials in the environment.
    storage_client = storage.Client()

    # Make an authenticated API request
    buckets = list(storage_client.list_buckets())
    print(buckets)

Ruby

# project_id = "Your Google Cloud project ID"

require "google/cloud/storage"

# If you don't specify credentials when constructing the client, the client
# library will look for credentials in the environment.
storage = Google::Cloud::Storage.new project: project_id

# Make an authenticated API request
storage.buckets.each do |bucket|
  puts bucket.name
end

Setting the environment variable allows you to provide credentials separately from your application, without making changes to application code when you deploy. Alternately, you can explicitly specify the path to the service account key file in your code. For more information, see the production guide.

What's next

Supervisa tus recursos estés donde estés

Obtén la app de Google Cloud Console para ayudarte a administrar tus proyectos.

Enviar comentarios sobre…