pub struct Session { /* private fields */ }Expand description
A session with the Comdirect API, managing tokens and automatic background refreshes.
Implementations§
Source§impl Session
impl Session
Sourcepub async fn new(
config: &ComdirectConfig,
refresh_token: Option<String>,
) -> Result<Self, AuthError>
pub async fn new( config: &ComdirectConfig, refresh_token: Option<String>, ) -> Result<Self, AuthError>
Initializes a new authenticated session with Comdirect.
This method orchestrates the complete OAuth2 handshake. Depending on whether a
refresh_token is provided, it will either attempt to resume an existing session
or perform a full “Interactive” login sequence.
§Authentication Flow
- Resumption: If
refresh_tokenisSome, it attempts arefresh_tokengrant.- If successful, it proceeds to obtain a new session ID and sets up the auto-refresh worker.
- If unsuccessful (e.g., token expired), it returns an error instead of falling back.
- Full Authentication: If no token is provided or resumption fails:
- Performs a
passwordgrant usinguserandpasswordfrom the config. - Triggers a Push-TAN challenge for session validation.
- Performs a
cd_secondarygrant to finalize the session.
- Performs a
§Background Worker
Upon successful creation, a background task is spawned that monitors token expiration. It proactively refreshes the access token 60 seconds before it expires (or at 10% of its life if shorter than 120s) to ensure uninterrupted API access.
§Token Persistence
To persist authentication across application restarts, provide an on_refresh_token
callback in the ComdirectConfig. This callback is triggered whenever a new
refresh token is successfully obtained (both during initial login and background refreshes).
§Example
use comdirect_rest_api::oauth2::{ComdirectConfig, Session};
use std::sync::Arc;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let config = ComdirectConfig {
user: "1234567".to_string(),
password: "your_password".to_string(),
client_id: "your_client_id".to_string(),
client_secret: "your_client_secret".to_string(),
on_awaits_user_confirm: Arc::new(|| Box::pin(async {
println!("Please confirm the TAN on your mobile device.");
})),
on_refresh_token: Some(Arc::new(|new_token| {
println!("New refresh token received: {}", new_token);
// Save this token to a database or secure file for next time
})),
};
// Try to resume with a previously saved token
let saved_token = Some("...token from database...".to_string());
let session = Session::new(&config, saved_token).await?;
println!("Session established! ID: {}", session.session_id().await);
Ok(())
}Sourcepub async fn session_id(&self) -> String
pub async fn session_id(&self) -> String
Returns the currently active session ID.