Skip to main content

18_session_tokens/
18_session_tokens.rs

1//! Session Tokens
2//!
3//! This example demonstrates:
4//! - Generating temporary session tokens
5//! - Session expiration and lifecycle
6//! - Refreshing credentials
7//!
8//! Scenario: Creating temporary credentials for a user.
9//!
10//! Run with: `cargo run --example 18_session_tokens`
11
12use std::sync::Arc;
13use tokio::sync::RwLock;
14use wami::arn::{TenantPath, WamiArn};
15use wami::context::WamiContext;
16use wami::service::{SessionTokenService, UserService};
17use wami::store::memory::InMemoryWamiStore;
18use wami::wami::identity::user::requests::CreateUserRequest;
19use wami::wami::sts::session_token::requests::GetSessionTokenRequest;
20
21#[tokio::main]
22async fn main() -> Result<(), Box<dyn std::error::Error>> {
23    println!("=== Session Tokens ===\n");
24
25    let store = Arc::new(RwLock::new(InMemoryWamiStore::default()));
26
27    // Create context
28    let context = WamiContext::builder()
29        .instance_id("123456789012")
30        .tenant_path(TenantPath::single(0))
31        .caller_arn(
32            WamiArn::builder()
33                .service(wami::arn::Service::Iam)
34                .tenant_path(TenantPath::single(0))
35                .wami_instance("123456789012")
36                .resource("user", "admin")
37                .build()?,
38        )
39        .is_root(false)
40        .build()?;
41
42    // Create user
43    let user_service = UserService::new(store.clone());
44    let alice_req = CreateUserRequest {
45        user_name: "alice".to_string(),
46        path: Some("/".to_string()),
47        permissions_boundary: None,
48        tags: None,
49    };
50    let alice = user_service.create_user(&context, alice_req).await?;
51    println!("Step 1: Created user alice");
52    println!("  ARN: {}\n", alice.arn);
53
54    // Generate session token
55    let sts_service = SessionTokenService::new(store.clone());
56
57    let token_req = GetSessionTokenRequest {
58        duration_seconds: Some(3600),
59        serial_number: None,
60        token_code: None,
61    };
62
63    let response = sts_service
64        .get_session_token(&context, token_req, &alice.arn)
65        .await?;
66
67    println!("Step 2: Generated session token");
68    println!("  Access Key: {}", response.credentials.access_key_id);
69    println!(
70        "  Secret Key: {}...",
71        &response.credentials.secret_access_key[..20]
72    );
73    println!(
74        "  Session Token: {}...",
75        &response.credentials.session_token[..30]
76    );
77    println!("  Expiration: {}", response.credentials.expiration);
78
79    println!("\n✅ Example completed successfully!");
80    println!("Key takeaways:");
81    println!("- Session tokens provide temporary credentials");
82    println!("- Credentials expire after specified duration");
83    println!("- Useful for temporary or delegated access");
84
85    Ok(())
86}