From 70a88ada6a4eab1999b6d9b843d33385de1053ad Mon Sep 17 00:00:00 2001 From: Wesley Irvin Date: Mon, 16 Dec 2024 19:57:45 -0500 Subject: [PATCH] Generate API Token Wrote function that generates a tailscale API token from our client id and client secret values that we have. Have checked with the logs on tailscale and can see that it is indeed generating the keys. This can be considered a solution to issue #6. --- src/lib.rs | 47 ++++++++++++++++++++++++++++++++++++----------- src/types.rs | 4 ++++ 2 files changed, 40 insertions(+), 11 deletions(-) create mode 100644 src/types.rs diff --git a/src/lib.rs b/src/lib.rs index 9901970..b8b4d4a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,20 +1,31 @@ use std::error::Error; use std::fs::read_to_string; +use oauth2::basic::BasicClient; +use oauth2::reqwest::http_client; +use oauth2::AccessToken; +use oauth2::AuthUrl; +use oauth2::ClientId; +use oauth2::ClientSecret; +use oauth2::TokenResponse; +use oauth2::TokenUrl; + +mod types; +use types::ClientAuth; + pub fn run() -> Result<(), Box> { let client_auth = read_client_auth()?; - println!("Client ID: {}", client_auth.client_id); - println!("Client Secret: {}", client_auth.client_secret); + println!("Client ID: {}", client_auth.id); + println!("Client Secret: {}", client_auth.secret); + + let access_token = get_api_token(client_auth.id, client_auth.secret)?; + + println!("Access Token: {access_token:#?}"); Ok(()) } -struct ClientAuth { - client_id: String, - client_secret: String, -} - fn read_client_auth() -> Result> { let mut id = String::new(); let mut secret = String::new(); @@ -29,8 +40,22 @@ fn read_client_auth() -> Result> { } } - Ok(ClientAuth { - client_id: id, - client_secret: secret, - }) + Ok(ClientAuth { id, secret }) +} + +fn get_api_token(client_id: String, client_secret: String) -> Result> { + let client = BasicClient::new( + ClientId::new(client_id), + Some(ClientSecret::new(client_secret)), + AuthUrl::new("https://api.tailscale.com/api/v2/oauth/token".to_string())?, + Some(TokenUrl::new( + "https://api.tailscale.com/api/v2/oauth/token".to_string(), + )?), + ); + + let token_result = client.exchange_client_credentials().request(http_client)?; + + let access_token = token_result.access_token().to_owned(); + + Ok(access_token) } diff --git a/src/types.rs b/src/types.rs new file mode 100644 index 0000000..90a7478 --- /dev/null +++ b/src/types.rs @@ -0,0 +1,4 @@ +pub struct ClientAuth { + pub id: String, + pub secret: String, +}