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 GCP Console, navigate to the Create service account key page.
  2. From the Service account dropdown, select New service account.
  3. Input a name into the form field.
  4. From the Role dropdown, select Project > Owner.

    Note: The Role field authorizes your service account to access resources. You can view and change this field later using Google Cloud Platform Console. If you are developing a production application, specify more granular permissions than Project > Owner. For more information, see granting roles to service accounts.
  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.

For the following commands, replace [NAME] with a service account name you define in the first step, and [PROJECT_ID] with your project ID.

  1. Create the service account.

    gcloud iam service-accounts create [NAME]
  2. Grant permissions to the service account.

    gcloud projects add-iam-policy-binding [PROJECT_ID] \
      --member "serviceAccount:[NAME]@[PROJECT_ID].iam.gserviceaccount.com" \
      --role "roles/owner"`
    Note: The Role field authorizes your service account to access resources. You can view and change this field later using Google Cloud Platform Console. If you are developing a production application, specify more granular permissions than Project > Owner. For more information, see granting roles to service accounts.
  3. Generate the key file. The following command creates a file named service-account.json in your current working directory.

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

Setting the environment variable

If you plan to use a service account with client library code, you need to set an environment variable.

Provide the credentials to your application code by setting the environment variable GOOGLE_APPLICATION_CREDENTIALS. Replace [PATH] with the location of the JSON file you downloaded in the previous step.

Linux or Mac OS X

export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

For example:

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"

Windows

With Powershell:

$env:GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

For example:

$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\service-account-file.json"

With command-line:

set GOOGLE_APPLICATION_CREDENTIALS=[PATH]

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.

Verifying authentication

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. For this reason, you can verify that authentication works by setting the environment variable, and then running client library code, such as the following example. If the request succeeds, authentication works.

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

What's next

Palautteen aihe:

Tämä sivu
Documentation