Override the default authentication credentials

The Google Cloud client libraries for Swift automatically configure the authentication credentials used to authenticate requests to Google Cloud. Some applications might need to override the default credentials. This document shows you how to override the default authentication credentials.

Before you begin

This document uses the Cloud Natural Language API. To enable this API, follow the Natural Language API setup guide.

Add the swift-google-cloud-language-v2 and swift-google-auth packages to your Package.swift dependencies, and create an API key to pass to your application.

For complete setup instructions for the Swift client libraries, see Quickstart: Get started with Swift.

Override the default credentials with an API key

API keys are text strings that grant access to some Google Cloud services. API keys require less configuration than other authentication methods. Before you use API keys, read Best practices for managing API keys to understand the associated security risks.

In this example, you configure the Natural Language API client to authenticate using an API key:

  1. Add the imports required to use the client library and authentication types:

    import Foundation
    import GoogleAuth
    import GoogleGax
    import GoogleCloudLanguageV2

  2. Write a function that receives the API key as a parameter:

    func sample(apiKey: String) async throws {

  3. Create a Credentials instance with the API key, and pass it to ClientOptions when initializing the client:

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

  4. Use the client to analyze the sentiment of a text document:

    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)")

Calling analyzeSentiment succeeds with the configured API key and returns an AnalyzeSentimentResponse containing the document's sentiment score and magnitude.

Complete code

The following example shows the complete code for this document:

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)")
}

What's next