logo
pub struct SessionMiddleware<Store: SessionStore> { /* private fields */ }
Expand description

A middleware for session management in Actix Web applications.

SessionMiddleware takes care of a few jobs:

  • Instructs the session storage backend to create/update/delete/retrieve the state attached to a session according to its status and the operations that have been performed against it;
  • Set/remove a cookie, on the client side, to enable a user to be consistently associated with the same session across multiple HTTP requests.

Use SessionMiddleware::new to initialize the session framework using the default parameters. To create a new instance of SessionMiddleware you need to provide:

  • an instance of the session storage backend you wish to use (i.e. an implementation of SessionStore);
  • a secret key, to sign or encrypt the content of client-side session cookie.
use actix_web::{web, App, HttpServer, HttpResponse, Error};
use actix_session::{Session, SessionMiddleware, storage::RedisActorSessionStore};
use actix_web::cookie::Key;

// The secret key would usually be read from a configuration file/environment variables.
fn get_secret_key() -> Key {
    // [...]
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let secret_key = get_secret_key();
    let redis_connection_string = "127.0.0.1:6379";
    HttpServer::new(move ||
            App::new()
            // Add session management to your application using Redis for session state storage
            .wrap(
                SessionMiddleware::new(
                    RedisActorSessionStore::new(redis_connection_string),
                    secret_key.clone()
                )
            )
            .default_service(web::to(|| HttpResponse::Ok())))
        .bind(("127.0.0.1", 8080))?
        .run()
        .await
}

If you want to customise use builder instead of new:

use actix_web::{cookie::Key, web, App, HttpServer, HttpResponse, Error};
use actix_session::{Session, SessionMiddleware, storage::RedisActorSessionStore, SessionLength};

// The secret key would usually be read from a configuration file/environment variables.
fn get_secret_key() -> Key {
    // [...]
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let secret_key = get_secret_key();
    let redis_connection_string = "127.0.0.1:6379";
    HttpServer::new(move ||
            App::new()
            // Customise session length!
            .wrap(
                SessionMiddleware::builder(
                    RedisActorSessionStore::new(redis_connection_string),
                    secret_key.clone()
                )
                .session_length(SessionLength::Predetermined {
                    max_session_length: Some(time::Duration::days(5)),
                })
                .build(),
            )
            .default_service(web::to(|| HttpResponse::Ok())))
        .bind(("127.0.0.1", 8080))?
        .run()
        .await
}

How did we choose defaults?

You should not regret adding actix-session to your dependencies and going to production using the default configuration. That is why, when in doubt, we opt to use the most secure option for each configuration parameter.

We expose knobs to change the default to suit your needs—i.e., if you know what you are doing, we will not stop you. But being a subject-matter expert should not be a requirement to deploy reasonably secure implementation of sessions.

Implementations

Use SessionMiddleware::new to initialize the session framework using the default parameters.

To create a new instance of SessionMiddleware you need to provide:

  • an instance of the session storage backend you wish to use (i.e. an implementation of `SessionStore);
  • a secret key, to sign or encrypt the content of client-side session cookie.

A fluent API to configure SessionMiddleware.

It takes as input the two required inputs to create a new instance of SessionMiddleware:

  • an instance of the session storage backend you wish to use (i.e. an implementation of `SessionStore);
  • a secret key, to sign or encrypt the content of client-side session cookie.

Trait Implementations

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Responses produced by the service.

Errors produced by the service.

The TransformService value created by this factory

Errors produced while building a transform service.

The future response value.

Creates and returns a new Transform component, asynchronously

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Should always be Self

The resulting type after obtaining ownership.

Creates owned data from borrowed data, usually by cloning. Read more

🔬 This is a nightly-only experimental API. (toowned_clone_into)

Uses borrowed data to replace owned data, usually by cloning. Read more

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more