Google Cloud IoT Core は 2023 年 8 月 16 日に廃止されます。詳細については、担当の Google Cloud アカウント チームにお問い合わせください。

アプリケーションの認証

このページでは、ユーザーが管理するサービス アカウントとその秘密鍵を使用して、Cloud IoT Core API に対してアプリケーションを認証する方法について説明します。

アプリケーションを使用して、レジストリとデバイスを管理できます。例については、Cloud IoT Core のコードサンプルをご覧ください。

サービス アカウントを使用して認証する

ユーザー管理サービス アカウントは、アプリケーションを表す Google アカウントの一種です。ユーザー管理サービス アカウントは、主にサーバー間 API 認証に使用されます。

Cloud IoT Core には 2 種類の認証があります。Cloud IoT Core に対してデバイスを認証する場合は、秘密鍵/公開鍵のペアJSON ウェブトークンを使用します。ただし、Cloud IoT Core API に対してアプリケーションを認証する場合は、ユーザーが管理するサービス アカウントの形式で GCP 認証を使用する必要があります。

ユーザー管理サービス アカウントには、さまざまな形式の独自の秘密鍵があります。 ユーザー管理のサービス アカウントの秘密鍵をアプリケーションに提供することで、認証情報を作成してアプリケーションを認証できます。

アプリケーションを認証するには、最も広くサポートされている柔軟なメソッドである、ユーザー管理のサービス アカウントと非公開の JSON キーを使用することをおすすめします。認証の開始の手順で、ユーザー管理のサービス アカウントを作成し、秘密 JSON キーをダウンロードできます。

次のサンプルは、ユーザー管理のサービス アカウントの秘密 JSON キーを使用して Cloud IoT Core API に対してアプリケーションを認証する方法を示しています。

C#

C# サンプルでは、JSON キーファイルは明示的に指定されていません。代わりに、GOOGLE_APPLICATION_CREDENTIALS 環境変数で指定された場所を使用します。そうすると、クライアント ライブラリが認証情報を暗黙的に判別できます。
public static CloudIotService CreateAuthorizedClient()
{
    GoogleCredential credential =
        GoogleCredential.GetApplicationDefaultAsync().Result;
    // Inject the Cloud IoT Core Service scope
    if (credential.IsCreateScopedRequired)
    {
        credential = credential.CreateScoped(new[]
        {
            CloudIotService.Scope.CloudPlatform // Used for IoT + PubSub + IAM
            //CloudIotService.Scope.Cloudiot // Can be used if not accessing Pub/Sub
        });
    }
    return new CloudIotService(new BaseClientService.Initializer
    {
        HttpClientInitializer = credential,
        GZipEnabled = false
    });
}

Go

Go のサンプルでは、JSON キーファイルが明示的に指定されていません。それよりも、GOOGLE_APPLICATION_CREDENTIALS 環境変数で指定されたロケーションを使用します。クライアント ライブラリによって、認証情報を暗黙的に判別できます。このサンプルは、レジストリの作成の状況でも使用されますが、実際の認証は後述します。

// createRegistry creates a IoT Core device registry associated with a PubSub topic
func createRegistry(w io.Writer, projectID string, region string, registryID string, topicName string) (*cloudiot.DeviceRegistry, error) {
	client, err := getClient()
	if err != nil {
		return nil, err
	}

	registry := cloudiot.DeviceRegistry{
		Id: registryID,
		EventNotificationConfigs: []*cloudiot.EventNotificationConfig{
			{
				PubsubTopicName: topicName,
			},
		},
	}

	parent := fmt.Sprintf("projects/%s/locations/%s", projectID, region)
	response, err := client.Projects.Locations.Registries.Create(parent, &registry).Do()
	if err != nil {
		return nil, err
	}

	fmt.Fprintln(w, "Created registry:")
	fmt.Fprintf(w, "\tID: %s\n", response.Id)
	fmt.Fprintf(w, "\tHTTP: %s\n", response.HttpConfig.HttpEnabledState)
	fmt.Fprintf(w, "\tMQTT: %s\n", response.MqttConfig.MqttEnabledState)
	fmt.Fprintf(w, "\tName: %s\n", response.Name)

	return response, nil
}

Java

Java のサンプルでは、JSON キーファイルが明示的に指定されていません。それよりも、GOOGLE_APPLICATION_CREDENTIALS 環境変数で指定されたロケーションを使用します。クライアント ライブラリによって、認証情報を暗黙的に判別できます。このサンプルは、レジストリの作成の状況でも使用されますが、実際の認証は後述します。
/** Create a registry for Cloud IoT. */
protected static void createRegistry(
    String cloudRegion, String projectId, String registryName, String pubsubTopicPath)
    throws GeneralSecurityException, IOException {
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault().createScoped(CloudIotScopes.all());
  JsonFactory jsonFactory = GsonFactory.getDefaultInstance();
  HttpRequestInitializer init = new HttpCredentialsAdapter(credential);
  final CloudIot service =
      new CloudIot.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, init)
          .setApplicationName(APP_NAME)
          .build();

  final String projectPath = "projects/" + projectId + "/locations/" + cloudRegion;
  final String fullPubsubPath = "projects/" + projectId + "/topics/" + pubsubTopicPath;

  DeviceRegistry registry = new DeviceRegistry();
  EventNotificationConfig notificationConfig = new EventNotificationConfig();
  notificationConfig.setPubsubTopicName(fullPubsubPath);
  List<EventNotificationConfig> notificationConfigs = new ArrayList<EventNotificationConfig>();
  notificationConfigs.add(notificationConfig);
  registry.setEventNotificationConfigs(notificationConfigs);
  registry.setId(registryName);

  DeviceRegistry reg =
      service.projects().locations().registries().create(projectPath, registry).execute();
  System.out.println("Created registry: " + reg.getName());
}

Node.js

// Client retrieved in callback
// const cloudRegion = 'us-central1';
// const projectId = 'adjective-noun-123';
// const registryId = 'my-registry';
// function errCb = lookupRegistry; // Lookup registry if already exists.
const iot = require('@google-cloud/iot');

// Lookup the pubsub topic
const topicPath = `projects/${projectId}/topics/${pubsubTopicId}`;

const iotClient = new iot.v1.DeviceManagerClient({
  // optional auth parameters.
});

async function createDeviceRegistry() {
  // Construct request
  const newParent = iotClient.locationPath(projectId, cloudRegion);
  const deviceRegistry = {
    eventNotificationConfigs: [
      {
        pubsubTopicName: topicPath,
      },
    ],
    id: registryId,
  };
  const request = {
    parent: newParent,
    deviceRegistry: deviceRegistry,
  };

  const [response] = await iotClient.createDeviceRegistry(request);

  console.log('Successfully created registry');
  console.log(response);
}

createDeviceRegistry();

PHP

PHP のサンプルでは、JSON キーファイルが明示的に指定されていません。それよりも、GOOGLE_APPLICATION_CREDENTIALS 環境変数で指定されたロケーションを使用します。クライアント ライブラリによって、認証情報を暗黙的に判別できます。このサンプルは、レジストリの作成の状況でも使用されますが、実際の認証は後述します。
use Google\Cloud\Iot\V1\DeviceManagerClient;

/**
 * List all registries in the project.
 *
 * @param string $projectId Google Cloud project ID
 * @param string $location (Optional) Google Cloud region
 */
function list_registries(
    $projectId,
    $location = 'us-central1'
) {
    print('Listing Registries' . PHP_EOL);

    // The Google Cloud Client Library automatically checks the environment
    // variable GOOGLE_APPLICATION_CREDENTIALS for the Service Account
    // credentials, and defaults scopes to [
    //    'https://www.googleapis.com/auth/cloud-platform',
    //    'https://www.googleapis.com/auth/cloudiot'
    // ].
    $deviceManager = new DeviceManagerClient();
    $locationName = $deviceManager->locationName($projectId, $location);

    $response = $deviceManager->listDeviceRegistries($locationName);

    foreach ($response->iterateAllElements() as $registry) {
        printf(' - Id: %s, Name: %s' . PHP_EOL,
            $registry->getId(),
            $registry->getName());
    }
}

Python

Python のサンプルでは、JSON キーファイルが明示的に指定されていません。それよりも、GOOGLE_APPLICATION_CREDENTIALS 環境変数で指定されたロケーションを使用します。そうすると、クライアント ライブラリが認証情報を暗黙的に判別できます。
# project_id = 'YOUR_PROJECT_ID'
# cloud_region = 'us-central1'
# pubsub_topic = 'your-pubsub-topic'
# registry_id = 'your-registry-id'
client = iot_v1.DeviceManagerClient()
parent = f"projects/{project_id}/locations/{cloud_region}"

if not pubsub_topic.startswith("projects/"):
    pubsub_topic = "projects/{}/topics/{}".format(project_id, pubsub_topic)

body = {
    "event_notification_configs": [{"pubsub_topic_name": pubsub_topic}],
    "id": registry_id,
}

try:
    response = client.create_device_registry(
        request={"parent": parent, "device_registry": body}
    )
    print("Created registry")
    return response
except HttpError:
    print("Error, registry not created")
    raise
except AlreadyExists:
    print("Error, registry already exists")
    raise

Ruby

Ruby のサンプルでは、JSON キーファイルが明示的に指定されていません。それよりも、GOOGLE_APPLICATION_CREDENTIALS 環境変数で指定されたロケーションを使用します。クライアント ライブラリによって、認証情報を暗黙的に判別できます。このサンプルは、レジストリの作成の状況でも使用されますが、実際の認証は後述します。
# project_id   = "Your Google Cloud project ID"
# location_id  = "The Cloud region that you created the registry in"
# registry_id  = "The Google Cloud IoT Core device registry identifier"
# pubsub_topic = "The Google Cloud PubSub topic to use for this registry"

require "google/apis/cloudiot_v1"

# Initialize the client and authenticate with the specified scope
Cloudiot   = Google::Apis::CloudiotV1
iot_client = Cloudiot::CloudIotService.new
iot_client.authorization = Google::Auth.get_application_default(
  "https://www.googleapis.com/auth/cloud-platform"
)

# The project / location where the registry is created.
parent = "projects/#{project_id}/locations/#{location_id}"

registry = Cloudiot::DeviceRegistry.new
registry.id = registry_id
registry.event_notification_configs = [Cloudiot::EventNotificationConfig.new]
registry.event_notification_configs[0].pubsub_topic_name = pubsub_topic

registry = iot_client.create_project_location_registry(
  parent, registry
)

puts "Created registry: #{registry.name}"