0

I want to be able to store a bearer token from the response body temporarily for about 900 seconds and be able to use the token whenever another function calls upon it. I have created the basic structure of creating the client and posting the request and getting a token back. Here is what I have so far:

#[derive(Debug, Deserialize)]
struct SecureToken {
    access_token: String,
    expiration_date_time: i32,
}

#[tokio::main]
async fn get_new_secure_token() {
    let mut map = HashMap::new();
        map.insert("client_id", "client_id");
        map.insert("client_secret", "client_secret");
        map.insert("scope", "scope");
        map.insert("grant_type", "client_credentials");

    let client = Client::new();

    let token_request = client
        .post("https://gatway.address")
        .form(&map)
        .send()
        .await
        .expect("");
        //.json::<TokenResponse>()
        //.await;
    
    match token_request.status() {
            StatusCode::OK => {
                let query_result = token_request.json::<SecureToken>().await;
                println!("{:#?}", query_result);
            },
            StatusCode::FORBIDDEN => {
                println!("Unable to connect to auth service");
            },
            StatusCode::BAD_REQUEST => {
                let bad_request = token_request.json::<BadRequest>().await;
                println!("Error: {:?}", bad_request);
            }
            s => println!("STATUS CODE: {:?}", s),
        };
}

Instead of printing the response, I want it to store the token temporarily for about 900 seconds along the lines of this:

let token_request = client
        .post("https://gatway.address")
        .form(&map)
        .send()
        .await
        .expect("");
        //.json::<TokenResponse>()
        //.await;

    match token_request.status() {
            StatusCode::OK => {
                let query_result = token_request.json::<SecureToken>().await;
                let token = quer
            },
            StatusCode::FORBIDDEN => {
                println!("Unable to connect to auth service");
            },
            StatusCode::BAD_REQUEST => {
                let bad_request = token_request.json::<BadRequest>().await;
                println!("Error: {:?}", bad_request);
            }
            s => println!("STATUS CODE: {:?}", s),
        };
}

But I don't know how to store the token nor add a expiration time to the token.

  • Great, once you do get stuck implementing that do [edit] your question to tell where you're stuck (error messages, expected/unexpected behavior, ...). There is also [tour] and [ask] that can help with what to add to your question. A [mre] would be very helpful. – cafce25 Dec 08 '22 at 00:18
  • cafce25, Thank you for your constructive criticism. I have taken the liberty and edited it to the best of my ability while taking the guides you have given me into consideration. – LIDAR_Freak Dec 08 '22 at 18:22

0 Answers0