替换默认身份验证凭证

适用于 Swift 的 Google Cloud 客户端库会自动配置用于对发送到Google Cloud的请求进行身份验证的身份验证凭证。某些应用可能需要替换默认凭据。本文档介绍了如何替换默认身份验证凭证。

准备工作

本文档使用 Cloud Natural Language API。如需启用此 API,请按照 Natural Language API 设置指南操作。

将 swift-google-cloud-language-v2 和 swift-google-auth 软件包添加到 Package.swift 依赖项中,然后创建 API 密钥以传递给应用。

如需查看 Swift 客户端库的完整设置说明,请参阅快速入门:Swift 使用入门。

使用 API 密钥覆盖默认凭证

API 密钥是文本字符串,用于授予对某些 Google Cloud 服务的访问权限。与其他身份验证方法相比,API 密钥所需的配置更少。在使用 API 密钥之前,请先阅读管理 API 密钥的最佳实践,了解相关的安全风险。

在此示例中,您将 Natural Language API 客户端配置为使用 API 密钥进行身份验证:

  1. 添加使用客户端库和身份验证类型所需的导入:

    import Foundation
    import GoogleAuth
    import GoogleGax
    import GoogleCloudLanguageV2

  2. 编写一个接收 API 密钥作为参数的函数:

    func sample(apiKey: String) async throws {

  3. 使用 API 密钥创建 Credentials 实例,并在初始化客户端时将其传递给 ClientOptions:

    let credentials = try Credentials(configuration: .apiKey(apiKey))
    let client = try LanguageServiceClient(
      ClientOptions().with { $0.credentials = credentials }
    )

  4. 使用客户端分析文本文档的情感:

    let document = Document().with {
      $0.type = .plainText
      $0.source = .content("Hello World!")
    }
    let response = try await client.analyzeSentiment(
      request: .init().with { $0.document = document })
    print("response=\(response)")

使用配置的 API 密钥成功调用 analyzeSentiment,并返回包含文档的情感 score 和 magnitude 的 AnalyzeSentimentResponse。

完整代码

以下示例显示了本文档的完整代码:

import Foundation
import GoogleAuth
import GoogleGax
import GoogleCloudLanguageV2

func sample(apiKey: String) async throws {
  let credentials = try Credentials(configuration: .apiKey(apiKey))
  let client = try LanguageServiceClient(
    ClientOptions().with { $0.credentials = credentials }
  )
  let document = Document().with {
    $0.type = .plainText
    $0.source = .content("Hello World!")
  }
  let response = try await client.analyzeSentiment(
    request: .init().with { $0.document = document })
  print("response=\(response)")
}

后续步骤