auth/
auth.rs

1use google_api_rust_client_unoffical::auth::service_account::ServiceAccountCredentials;
2use std::{path::PathBuf, str::FromStr};
3use anyhow::Result;
4
5#[tokio::main]
6async fn main() -> Result<()> {
7
8    // service account credentials from file
9    let filepath: PathBuf = PathBuf::from_str("credentials.json")?;
10    let credentials = ServiceAccountCredentials::from_service_account_file(filepath)?;
11    let scoped_credentials = credentials.with_scopes(vec!["https://www.googleapis.com/auth/cloud-translation"]);
12    let mut subjected_crentials = scoped_credentials.with_subject("itsuki@example.com");
13    let token = subjected_crentials.get_access_token().await?;
14    println!("token: {}", token);
15
16    // service account credentials from json
17    let credentials_json = serde_json::json!({
18        "type": "service_account",
19        "project_id": "xxx",
20        "private_key_id": "xxx",
21        "private_key": "-----BEGIN PRIVATE KEY-----\nsome_key\n-----END PRIVATE KEY-----\n",
22        "client_email": "xxx@example.com",
23        "client_id": "xxx",
24        "auth_uri": "https://accounts.google.com/o/oauth2/auth",
25        "token_uri": "https://oauth2.googleapis.com/token",
26        "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
27        "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/xxx",
28        "universe_domain": "googleapis.com"
29    }).to_string();
30    let credentials = ServiceAccountCredentials::from_service_account_info(credentials_json)?;
31    let scoped_credentials = credentials.with_scopes(vec!["https://www.googleapis.com/auth/cloud-translation"]);
32    let mut subjected_crentials = scoped_credentials.with_subject("itsuki@example.com");
33    let token = subjected_crentials.get_access_token().await?;
34    println!("token: {}", token);
35
36    Ok(())
37}