Hello everyone,
I'm currently working on a Rust web application using Actix and Actix Session Middleware. I'm trying to implement session management using cookies, but I'm encountering an issue where the session cookie fails cryptographic checks. Here are the details of my setup:
What I'm Trying to Do:
I want to store and retrieve session data using cookies in an Actix web application. The session setup involves using SessionMiddleware
with CookieSessionStore
and a generated cryptographic key.
My Setup:
- Actix version:
actix-session = { version = "0.10.0", features = ["cookie-session"] }
actix-web = "4.9.0"
env_logger = "0.11.5"
log = "0.4.22"
serde = { version = "1.0.208", features = ["derive"] }
- Session configuration:
- Middleware is set up with
CookieSessionStore
and a key generated usingKey::generate()
. - Cookie settings include
cookie_secure(false)
for local development andSameSite::Strict
.
- Code snippet:
use actix_web::{App, HttpServer};
use actix_session::{SessionMiddleware, config::{BrowserSession, CookieContentSecurity}, storage::CookieSessionStore};
use actix_web::cookie::{Key, SameSite};
use session_test::routes::init;
use env_logger::Env;
fn session_middleware() -> SessionMiddleware<CookieSessionStore> {
let key = Key::generate(); // Gere uma chave aleatória para produção
SessionMiddleware::builder(
CookieSessionStore::default(),
key
)
.cookie_name(String::from("my-kata-cookie"))
.cookie_secure(false) // Defina como false para localhost, true para produção
.session_lifecycle(BrowserSession::default())
.cookie_same_site(SameSite::Strict)
.cookie_content_security(CookieContentSecurity::Private)
.cookie_http_only(true)
.build()
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
env_logger::init_from_env(Env::default().default_filter_or("info")); // Inicializa o logger
HttpServer::new(|| {
App::new()
.configure(init) // Certifique-se de que 'init' está no módulo correto
.wrap(session_middleware())
})
.bind("127.0.0.1:8080")?
.run()
.await
}
use actix_web::{get, post, web, HttpResponse, web::Json};
use serde::Deserialize;
use actix_session::Session;
use log::info;
#[derive(Deserialize)]
struct Message {
message: String,
}
#[get("/get_session")]
async fn get_session(session: Session) -> impl actix_web::Responder {
match session.get::<String>("message") {
Ok(Some(message)) => {
info!("Sessão encontrada: {}", message);
HttpResponse::Ok().body(format!("Session: {}", message))
},
Ok(None) => {
info!("Nenhum valor de sessão encontrado.");
HttpResponse::NotFound().body("No session value found.")
},
Err(e) => {
info!("Erro ao recuperar o valor da sessão: {:?}", e);
HttpResponse::InternalServerError().body("Error retrieving session value.")
},
}
}
#[post("/set_session")]
async fn set_session(session: Session, msg: Json<Message>) -> impl actix_web::Responder {
match session.insert("message", msg.message.clone()) {
Ok(_) => {
info!("Sessão criada com mensagem: {}", msg.message);
HttpResponse::Created().body("Created.")
},
Err(e) => {
info!("Erro ao definir a sessão: {:?}", e);
HttpResponse::InternalServerError().body("Error.")
},
}
}
pub fn init(cfg: &mut web::ServiceConfig) {
cfg.service(get_session)
.service(set_session);
}
When I set a session value using a POST request and then try to retrieve it with a GET request, I receive the following log message:
[WARN actix_session::middleware] The session cookie attached to the incoming request failed to pass cryptographic checks (signature verification/decryption).
This is a test project but my goal is to implement this feature in a project where I have a session.rs and I need to maintain this session and periodically check if the Cookie is valid and I need to re-authenticate.