Axum Session

repository·main·Indexed 41 days ago

https://github.com/ascendingcreations/axumsession

A high-performance session management middleware for the Axum web framework (v0.21.0). It supports HTTP and REST modes, providing flexible storage options including in-memory, Redis, MongoDB, SurrealDB, and SQLx. Key features include signed cookies, data encryption, SessionID renewal, and performance optimization via Fastbloom key storage.

Tokens
15.4K
Snippets
56
Records
72
Agent score
52%

What's inside Axum Session

  1. Optimize performance with Fastbloom key storage

    main

    To reduce database lookups and improve bandwidth/latency, enable the key-store feature. This uses Fastbloom for in-process key storage.

    Configuration:

    • The use_bloom_filters option is enabled by default.
    • You can tune performance using with_filter_expected_elements and with_filter_false_positive_probability in your SessionConfig.
    • Trade-off: Higher values for these settings decrease the chance of false positives but increase server-side RAM usage.
  2. How Axum Session works

    main

    Axum Session is a middleware for Axum that manages session data.

    Core Mechanics:

    • Storage: Internally uses a MemoryStore (via dashmap for high throughput) and can optionally sync to a persistent database for long-term storage.
    • Identification: Uses generated Session UUIDs stored in either Cookies or Headers to sync back to the session store.
    • Data Handling: Uses Serde for serialization, allowing you to store any Serde-supported types in the session.
    • Security: Supports Cookie/Header signing (integrity/authenticity), database session encryption (confidentiality/integrity), and SessionID renewal.
    • Extensibility: Implements a DatabasePool trait, allowing you to implement your own sub-storage layer.
  3. Set up a default Axum Session with SQLx

    main

    To use axum_session with a persistent SQLx database, follow this pattern:

    1. Connect to your database to get a pool.
    2. Configure the session using SessionConfig (e.g., setting a table name).
    3. Initialize the SessionStore with the database pool and config.
    4. Add the SessionLayer to your Axum Router.
    5. Access the session in handlers using the Session<T> extractor.
    use sqlx::{ConnectOptions, postgres::{PgPoolOptions, PgConnectOptions}};
    use std::net::SocketAddr;
    use axum_session::{Session, SessionPgPool, SessionConfig, SessionStore, SessionLayer};
    use axum::{
        Router,
        routing::get,
    };
    use tokio::net::TcpListener;
    
    #[tokio::main]
    async fn main() {
    
        let pool = connect_to_database().await.unwrap();
    
        // This Defaults as normal Cookies.
        let session_config = SessionConfig::default()
            .with_table_name("sessions_table");
    
        // create SessionStore and initiate the database tables
        let session_store = SessionStore::<SessionPgPool>::new(Some(pool.clone().into()), session_config).await.unwrap();
    
        // build our application with some routes
        let app = Router::new()
            .route("/greet", get(greet))
            .layer(SessionLayer::new(session_store));
    
        // run it
        let addr = SocketAddr::from(([0, 0, 0, 0], 8000));
    
        println!("listening on {}", addr);
        let listener = TcpListener::bind(addr).await.unwrap();
        axum::serve(listener, app).await.unwrap();
    }
    
    async fn greet(session: Session<SessionPgPool>) -> String {
        let mut count: usize = session.get("count").unwrap_or(0);
    
        count += 1;
        session.set("count", count);
    
        count.to_string()
    }
    
    async fn connect_to_database() -> anyhow::Result<sqlx::Pool<sqlx::Postgres>> {
        // ...
        unimplemented!()
    }
  4. Use axum_session_redispool for Redis session storage

    main

    The axum_session_redispool crate provides a session storage backend for axum-session using a Redis connection pool. It allows you to manage user sessions in Redis, which is suitable for distributed applications requiring shared session state.

    By default, it exports the necessary types and functions from redis_pool. If the redis-clusterdb feature is enabled, it also provides support for Redis Cluster environments via redis_cluster_pool.

    // Note: This is a library entrypoint. 
    // Usage typically involves importing the session store from this crate
    // and passing it to the axum-session middleware configuration.