对应用进行身份验证

本页面介绍如何使用用户管理的服务帐号及其私钥向 Cloud IoT Core API 验证应用。

您可以使用应用来管理注册表和设备。如需查看示例,请参阅 Cloud IoT Core 代码示例

使用服务帐号进行身份验证

用户管理的服务帐号是代表应用的 Google 帐号类型。 用户管理的服务帐号主要用于服务器到 API 身份验证。

Cloud IoT Core 使用两种类型的身份验证。向 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 = JacksonFactory.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}"