Skip to content
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions guide/samples/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -68,3 +68,6 @@ test-case.workspace = true
run-integration-tests = []
log-integration-tests = []
run-large-downloads = []

[lints]
workspace = true
4 changes: 4 additions & 0 deletions guide/samples/src/authentication.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,7 @@
pub mod adc;
pub mod api_key;
pub mod impersonation;
#[cfg(google_cloud_unstable_id_token)]
pub mod request_id_token;
#[cfg(google_cloud_unstable_id_token)]
pub mod verify_id_token;
49 changes: 49 additions & 0 deletions guide/samples/src/authentication/request_id_token.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// [START rust_auth_request_id_token] ANCHOR: all
// [START rust_auth_request_id_token_parameters] ANCHOR: request_id_token_parameters
// # Parameters
// * `audience`: The audience for the ID token.
pub async fn sample(audience: &str) -> anyhow::Result<String> {
// [END rust_auth_request_id_token_parameters] ANCHOR_END: request_id_token_parameters
// [START rust_auth_request_id_token_use] ANCHOR: request_id_token_use
use google_cloud_auth::credentials::idtoken::Builder;
// [END rust_auth_request_id_token_use] ANCHOR_END: request_id_token_use

// [START rust_auth_request_id_token_client] ANCHOR: request_id_token_client
let client = Builder::new(audience).build()?;
// [END rust_auth_request_id_token_client] ANCHOR_END: request_id_token_client

// [START rust_auth_request_id_token_call] ANCHOR: request_id_token_call
let id_token = client.id_token().await?;
println!("ID Token: {id_token:?}");
// [END rust_auth_request_id_token_call] ANCHOR_END: request_id_token_call
Ok(id_token)
}

pub async fn send_id_token(id_token: &str) -> anyhow::Result<()> {
// [START request_id_token_send] ANCHOR: request_id_token_send
use reqwest;

let client = reqwest::Client::new();
let target_url = format!("{audience}/api/method");
client.get(target_url)
.bearer_auth(id_token)
.send()
.await?;
// [END request_id_token_send] ANCHOR_END: request_id_token_send
Ok(())
}
// [END rust_auth_request_id_token] ANCHOR_END: all
36 changes: 36 additions & 0 deletions guide/samples/src/authentication/verify_id_token.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// [START rust_auth_verify_id_token] ANCHOR: all
// [START rust_auth_id_verify_token_parameters] ANCHOR: verify_id_token_parameters
// # Parameters
// * `token`: The ID token string to verify.
// * `audience`: The expected audience of the ID token.
pub async fn sample(token: &str, audience: &str) -> anyhow::Result<()> {
// [END rust_auth_id_verify_token_parameters] ANCHOR_END: verify_id_token_parameters
// [START rust_auth_verify_id_token_use] ANCHOR: verify_id_token_use
use google_cloud_auth::credentials::idtoken::verifier::Builder as IdTokenVerifierBuilder;
// [END rust_auth_verify_id_token_use] ANCHOR_END: verify_id_token_use

// [START rust_auth_id_verify_token_verifier] ANCHOR: verify_id_token_verifier
let verifier = IdTokenVerifierBuilder::new(audience).build();
// [END rust_auth_id_verify_token_verifier] ANCHOR_END: verify_id_token_verifier

// [START rust_auth_id_verify_token_verify_call] ANCHOR: verify_id_token_verify_call
let claims = verifier.verify(token).await?;
println!("ID Token claims {claims:?}");
// [END rust_auth_id_verify_token_verify_call] ANCHOR_END: verify_id_token_verify_call
Ok(())
}
// [END rust_auth_id_verify_token] ANCHOR_END: all
11 changes: 11 additions & 0 deletions guide/samples/tests/driver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,17 @@ mod driver {
Ok(())
}

#[cfg(all(test, google_cloud_unstable_id_token))]
#[tokio::test(flavor = "multi_thread")]
async fn id_token() -> anyhow::Result<()> {
let audience = "https://example.com/";
let id_token =
user_guide_samples::authentication::request_id_token::sample(audience).await?;
user_guide_samples::authentication::verify_id_token::sample(id_token.as_str(), audience)
.await?;
Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn endpoint() -> anyhow::Result<()> {
let project_id = std::env::var("GOOGLE_CLOUD_PROJECT").unwrap();
Expand Down
4 changes: 3 additions & 1 deletion guide/src/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ limitations under the License.
- [Setting up your development environment](setting_up_your_development_environment.md)
- [Setting up Rust on Cloud Shell](setting_up_rust_on_cloud_shell.md)
- [How to initialize a client](initialize_a_client.md)
- [Authentication](credentials.md)
- [Override the authentication credentials](credentials/override.md)
- [ID Tokens](credentials/id_tokens.md)
- [Generate text using the Vertex AI Gemini API](generate_text_using_the_vertex_ai_gemini_api.md)
- [Using Google Cloud Storage](storage.md)
- [Push data on object writes](storage/queue.md)
Expand All @@ -31,7 +34,6 @@ limitations under the License.
- [Update a resource using a field mask](update_resource.md)
- [Override the default endpoint](endpoint.md)
- [Configuring retry policies](configuring_retry_policies.md)
- [Override the authentication credentials](credentials.md)
- [Error handling](error_handling.md)
- [Examine error details](examine_error_details.md)
- [Handling binding errors](binding_errors.md)
Expand Down
103 changes: 8 additions & 95 deletions guide/src/credentials.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@ See the License for the specific language governing permissions and
limitations under the License.
-->

# Override authentication credentials
# Authentication

The Google Cloud client libraries for Rust automatically authenticate your
requests to Google Cloud services. Some applications may need to override the
default authentication. This guide shows you how to override the default.
requests to Google Cloud services. This section shows you how use the different
authentication methods.

## Prerequisites

Expand Down Expand Up @@ -63,92 +63,6 @@ Use this client as usual:
{{#include ../samples/src/authentication/adc.rs:rust_auth_adc_call}}
```

## Override the default credentials: API keys

[API keys] are text strings that grant access to some Google Cloud services.
Using API keys may simplify development as they require less configuration than
other [authentication methods]. There are some risks associated with API keys,
we recommended you read [Best practices for managing API keys] if you plan to
use them.

First, add some use declarations to simplify the rest of the example:

```rust,ignore
{{#include ../samples/src/authentication/api_key.rs:rust_auth_api_key_use}}
```

This example receives the API key string as an input parameter:

```rust,ignore
{{#include ../samples/src/authentication/api_key.rs:rust_auth_api_key_parameter}}
```

Use the API Keys [Builder][api keys builder] to create the credentials:

```rust,ignore
{{#include ../samples/src/authentication/api_key.rs:rust_auth_api_key_credentials}}
```

Initialize the client using the result:

```rust,ignore
{{#include ../samples/src/authentication/api_key.rs:rust_auth_api_key_client}}
```

Use this client as usual:

```rust,ignore
{{#include ../samples/src/authentication/api_key.rs:rust_auth_api_key_call}}
```

## Override the default credentials: service account impersonation

Service account impersonation allows you to make API calls on behalf of a
service account. [Use service account impersonation] discusses this form of
authentication in detail.

When you use service account impersonation, you start with an authenticated
principal (your user account or a service account) and request short-lived
credentials for a service account that has the authorization that your use case
requires.

It is more secure than downloading a service account key for the target service
account, as you do not need to hold the credentials in the file system or even
in memory.

First, add some use declarations to simplify the rest of the example:

```rust,ignore
{{#include ../samples/src/authentication/impersonation.rs:rust_auth_impersonation_use}}
```

This example receives the service account identifier as an input parameter. This
can be the service account email or the unique numeric id assigned by Google
when you created the service account:

```rust,ignore
{{#include ../samples/src/authentication/impersonation.rs:rust_auth_impersonation_parameter}}
```

Use the impersonated service account [Builder][impersonated builder] to create
the credentials:

```rust,ignore
{{#include ../samples/src/authentication/impersonation.rs:rust_auth_impersonation_credentials}}
```

Initialize the client using the result:

```rust,ignore
{{#include ../samples/src/authentication/impersonation.rs:rust_auth_impersonation_client}}
```

Use this client as usual:

```rust,ignore
{{#include ../samples/src/authentication/impersonation.rs:rust_auth_impersonation_call}}
```

## More Information

Learn about other authentication methods in the Rust client libraries:
Expand All @@ -159,18 +73,17 @@ Learn about other authentication methods in the Rust client libraries:
[Workload identity federation] with the Rust client libraries.
- [Service Accounts][service account builder]: to initialize credentials from a
[service account key].
- [Override Credentials]: to override the default credentials.
- [ID Tokens]: obtains and verify [OIDC ID Tokens].

[anonymous builder]: https://docs.rs/google-cloud-auth/latest/google_cloud_auth/credentials/anonymous/struct.Builder.html
[api keys]: https://cloud.google.com/docs/authentication/api-keys
[api keys builder]: https://docs.rs/google-cloud-auth/latest/google_cloud_auth/credentials/api_key_credentials/struct.Builder.html
[authentication methods]: https://cloud.google.com/docs/authentication
[best practices for managing api keys]: https://cloud.google.com/docs/authentication/api-keys-best-practices
[cloud natural language api]: https://cloud.google.com/natural-language
[external account builder]: https://docs.rs/google-cloud-auth/latest/google_cloud_auth/credentials/external_account/struct.Builder.html
[how application default credentials work]: https://cloud.google.com/docs/authentication/application-default-credentials
[impersonated builder]: https://docs.rs/google-cloud-auth/latest/google_cloud_auth/credentials/impersonated/struct.Builder.html
[id tokens]: credentials/id_tokens.md
[oidc id tokens]: https://cloud.google.com/docs/authentication/token-types#identity-tokens
[override credentials]: credentials/override.md
[service account builder]: https://docs.rs/google-cloud-auth/latest/google_cloud_auth/credentials/impersonated/struct.Builder.html
[service account key]: https://cloud.google.com/iam/docs/service-account-creds#key-types
[service quickstart]: https://cloud.google.com/natural-language/docs/setup
[use service account impersonation]: https://cloud.google.com/docs/authentication/use-service-account-impersonation
[workload identity federation]: https://cloud.google.com/iam/docs/workload-identity-federation
Loading
Loading